Example usage for java.util.concurrent.atomic AtomicBoolean set

List of usage examples for java.util.concurrent.atomic AtomicBoolean set

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicBoolean set.

Prototype

public final void set(boolean newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:org.apache.tez.dag.app.rm.TestContainerReuse.java

@Test(timeout = 30000l)
public void testReuseAcrossVertices() throws IOException, InterruptedException, ExecutionException {
    Configuration tezConf = new Configuration(new YarnConfiguration());
    tezConf.setBoolean(TezConfiguration.TEZ_AM_CONTAINER_REUSE_ENABLED, true);
    tezConf.setLong(TezConfiguration.TEZ_AM_CONTAINER_REUSE_LOCALITY_DELAY_ALLOCATION_MILLIS, 1l);
    tezConf.setLong(TezConfiguration.TEZ_AM_CONTAINER_IDLE_RELEASE_TIMEOUT_MIN_MILLIS, 2000l);
    tezConf.setInt(TezConfiguration.TEZ_AM_SESSION_MIN_HELD_CONTAINERS, 1);
    RackResolver.init(tezConf);/*from   w  ww . j  a  va  2 s .  co m*/
    TaskSchedulerAppCallback mockApp = mock(TaskSchedulerAppCallback.class);

    CapturingEventHandler eventHandler = new CapturingEventHandler();
    TezDAGID dagID = TezDAGID.getInstance("0", 0, 0);

    AMRMClient<CookieContainerRequest> rmClientCore = new AMRMClientForTest();
    TezAMRMClientAsync<CookieContainerRequest> rmClient = spy(new AMRMClientAsyncForTest(rmClientCore, 100));
    String appUrl = "url";
    String appMsg = "success";
    AppFinalStatus finalStatus = new AppFinalStatus(FinalApplicationStatus.SUCCEEDED, appMsg, appUrl);

    doReturn(finalStatus).when(mockApp).getFinalAppStatus();

    AppContext appContext = mock(AppContext.class);
    AMContainerMap amContainerMap = new AMContainerMap(mock(ContainerHeartbeatHandler.class),
            mock(TaskAttemptListener.class), new ContainerContextMatcher(), appContext);
    AMNodeTracker amNodeTracker = new AMNodeTracker(eventHandler, appContext);
    doReturn(amContainerMap).when(appContext).getAllContainers();
    doReturn(amNodeTracker).when(appContext).getNodeTracker();
    doReturn(DAGAppMasterState.RUNNING).when(appContext).getAMState();
    doReturn(true).when(appContext).isSession();
    doReturn(dagID).when(appContext).getCurrentDAGID();
    doReturn(mock(ClusterInfo.class)).when(appContext).getClusterInfo();

    TaskSchedulerEventHandler taskSchedulerEventHandlerReal = new TaskSchedulerEventHandlerForTest(appContext,
            eventHandler, rmClient, new AlwaysMatchesContainerMatcher());
    TaskSchedulerEventHandler taskSchedulerEventHandler = spy(taskSchedulerEventHandlerReal);
    taskSchedulerEventHandler.init(tezConf);
    taskSchedulerEventHandler.start();

    TaskSchedulerWithDrainableAppCallback taskScheduler = (TaskSchedulerWithDrainableAppCallback) ((TaskSchedulerEventHandlerForTest) taskSchedulerEventHandler)
            .getSpyTaskScheduler();
    TaskSchedulerAppCallbackDrainable drainableAppCallback = taskScheduler.getDrainableAppCallback();

    AtomicBoolean drainNotifier = new AtomicBoolean(false);
    taskScheduler.delayedContainerManager.drainedDelayedContainersForTest = drainNotifier;

    Resource resource1 = Resource.newInstance(1024, 1);
    String[] host1 = { "host1" };

    String[] racks = { "/default-rack" };
    Priority priority1 = Priority.newInstance(3);
    Priority priority2 = Priority.newInstance(4);

    TezVertexID vertexID1 = TezVertexID.getInstance(dagID, 1);
    TezVertexID vertexID2 = TezVertexID.getInstance(dagID, 2);

    //Vertex 1, Task 1, Attempt 1, host1
    TezTaskAttemptID taID11 = TezTaskAttemptID.getInstance(TezTaskID.getInstance(vertexID1, 1), 1);
    TaskAttempt ta11 = mock(TaskAttempt.class);
    doReturn(vertexID1).when(ta11).getVertexID();
    AMSchedulerEventTALaunchRequest lrEvent11 = createLaunchRequestEvent(taID11, ta11, resource1, host1, racks,
            priority1);

    //Vertex2, Task1, Attempt 1, host1
    TezTaskAttemptID taID21 = TezTaskAttemptID.getInstance(TezTaskID.getInstance(vertexID2, 1), 1);
    TaskAttempt ta21 = mock(TaskAttempt.class);
    doReturn(vertexID2).when(ta21).getVertexID();
    AMSchedulerEventTALaunchRequest lrEvent21 = createLaunchRequestEvent(taID21, ta21, resource1, host1, racks,
            priority2);

    // Send launch request for task 1 onle, deterministic assignment to this task.
    taskSchedulerEventHandler.handleEvent(lrEvent11);

    Container container1 = createContainer(1, host1[0], resource1, priority1);

    // One container allocated.
    drainNotifier.set(false);
    taskScheduler.onContainersAllocated(Collections.singletonList(container1));
    TestTaskSchedulerHelpers.waitForDelayedDrainNotify(drainNotifier);
    drainableAppCallback.drain();
    verify(taskSchedulerEventHandler).taskAllocated(eq(ta11), any(Object.class), eq(container1));

    // Send launch request for task2 (vertex2)
    taskSchedulerEventHandler.handleEvent(lrEvent21);

    // Task assigned to container completed successfully.
    // Container should  be assigned to task21.
    taskSchedulerEventHandler
            .handleEvent(new AMSchedulerEventTAEnded(ta11, container1.getId(), TaskAttemptState.SUCCEEDED));
    drainableAppCallback.drain();
    verify(taskScheduler).deallocateTask(eq(ta11), eq(true));
    verify(taskSchedulerEventHandler).taskAllocated(eq(ta21), any(Object.class), eq(container1));
    verify(rmClient, times(0)).releaseAssignedContainer(eq(container1.getId()));

    // Task 2 completes.
    taskSchedulerEventHandler
            .handleEvent(new AMSchedulerEventTAEnded(ta21, container1.getId(), TaskAttemptState.SUCCEEDED));
    verify(rmClient, times(0)).releaseAssignedContainer(eq(container1.getId()));

    LOG.info("Sleeping to ensure that the scheduling loop runs");
    Thread.sleep(3000l);
    // container should not get released due to min held containers
    verify(rmClient, times(0)).releaseAssignedContainer(eq(container1.getId()));

    taskScheduler.close();
    taskSchedulerEventHandler.close();
}

From source file:eu.esdihumboldt.hale.ui.service.instance.internal.orient.OrientInstanceService.java

/**
 * Perform the transformation/*from   w  w w .ja  v a 2  s. c  o  m*/
 * 
 * @return if the transformation was successful
 */
protected boolean performTransformation() {
    final TransformationService ts = getTransformationService();
    if (ts == null) {
        log.userError("No transformation service available");
        return false;
    }

    final AtomicBoolean transformationFinished = new AtomicBoolean(false);
    final AtomicBoolean transformationCanceled = new AtomicBoolean(false);
    IRunnableWithProgress op = new IRunnableWithProgress() {

        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                Alignment alignment = getAlignmentService().getAlignment();
                if (alignment.getActiveTypeCells().isEmpty()) {
                    // early exit if there are no type relations
                    return;
                }

                // determine if there are any active type cells w/o source
                boolean transformEmpty = false;
                for (Cell cell : alignment.getActiveTypeCells()) {
                    if (cell.getSource() == null || cell.getSource().isEmpty()) {
                        transformEmpty = true;
                        break;
                    }
                }

                InstanceCollection sources = getInstances(DataSet.SOURCE);
                if (!transformEmpty && sources.isEmpty()) {
                    return;
                }

                HaleOrientInstanceSink sink = new HaleOrientInstanceSink(transformed, true);
                TransformationReport report;
                ATransaction trans = log.begin("Instance transformation");
                try {
                    report = ts.transform(alignment, sources, sink, HaleUI.getServiceProvider(),
                            new ProgressMonitorIndicator(monitor));

                    // publish report
                    ReportService rs = PlatformUI.getWorkbench().getService(ReportService.class);
                    rs.addReport(report);
                } finally {
                    try {
                        sink.close();
                    } catch (IOException e) {
                        // ignore
                    }
                    trans.end();
                }
            } finally {
                // remember if canceled
                if (monitor.isCanceled()) {
                    transformationCanceled.set(true);
                }

                // transformation finished
                transformationFinished.set(true);
            }
        }

    };

    try {
        ThreadProgressMonitor.runWithProgressDialog(op, ts.isCancelable());
    } catch (Throwable e) {
        log.error("Error starting transformation process", e);
    }

    // wait for transformation to complete
    HaleUI.waitFor(transformationFinished);

    return !transformationCanceled.get();
}

From source file:org.apache.hadoop.yarn.server.nodemanager.TestNodeStatusUpdater.java

@Test
public void testConcurrentAccessToSystemCredentials() {
    final Map<ApplicationId, ByteBuffer> testCredentials = new HashMap<>();
    ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[300]);
    ApplicationId applicationId = ApplicationId.newInstance(123456, 120);
    testCredentials.put(applicationId, byteBuffer);

    final List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>());

    final int NUM_THREADS = 10;
    final CountDownLatch allDone = new CountDownLatch(NUM_THREADS);
    final ExecutorService threadPool = Executors.newFixedThreadPool(NUM_THREADS);

    final AtomicBoolean stop = new AtomicBoolean(false);

    try {/*from  ww w  .j  av  a  2  s  .  co  m*/
        for (int i = 0; i < NUM_THREADS; i++) {
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        for (int i = 0; i < 100 && !stop.get(); i++) {
                            NodeHeartbeatResponse nodeHeartBeatResponse = newNodeHeartbeatResponse(0,
                                    NodeAction.NORMAL, null, null, null, null, 0);
                            nodeHeartBeatResponse.setSystemCredentialsForApps(testCredentials);
                            NodeHeartbeatResponseProto proto = ((NodeHeartbeatResponsePBImpl) nodeHeartBeatResponse)
                                    .getProto();
                            Assert.assertNotNull(proto);
                        }
                    } catch (Throwable t) {
                        exceptions.add(t);
                        stop.set(true);
                    } finally {
                        allDone.countDown();
                    }
                }
            });
        }

        int testTimeout = 2;
        Assert.assertTrue("Timeout waiting for more than " + testTimeout + " " + "seconds",
                allDone.await(testTimeout, TimeUnit.SECONDS));
    } catch (InterruptedException ie) {
        exceptions.add(ie);
    } finally {
        threadPool.shutdownNow();
    }
    Assert.assertTrue("Test failed with exception(s)" + exceptions, exceptions.isEmpty());
}

From source file:com.google.dart.java2dart.SyntaxTranslator.java

@Override
public boolean visit(org.eclipse.jdt.core.dom.ClassInstanceCreation node) {
    IMethodBinding binding = node.resolveConstructorBinding();
    String signature = JavaUtils.getJdtSignature(binding);
    TypeName typeNameNode = (TypeName) translate(node.getType());
    final List<Expression> arguments = translateArguments(binding, node.arguments());
    final ClassDeclaration innerClass;
    {//w  w  w  .j  a  va 2  s .  co  m
        AnonymousClassDeclaration anoDeclaration = node.getAnonymousClassDeclaration();
        if (anoDeclaration != null) {
            ITypeBinding superclass = anoDeclaration.resolveBinding().getSuperclass();
            signature = superclass.getKey() + StringUtils.substringAfter(signature, ";");
            String name = typeNameNode.getName().getName().replace('.', '_');
            name = name + "_" + context.generateTechnicalAnonymousClassIndex();
            innerClass = declareInnerClass(binding, anoDeclaration, name, ArrayUtils.EMPTY_STRING_ARRAY);
            typeNameNode = typeName(name);
            // prepare enclosing type
            final ITypeBinding enclosingTypeBinding = getEnclosingTypeBinding(node);
            final SimpleIdentifier enclosingTypeRef;
            final AtomicBoolean addEnclosingTypeRef = new AtomicBoolean();
            {
                if (enclosingTypeBinding != null) {
                    enclosingTypeRef = identifier(enclosingTypeBinding.getName() + "_this");
                    // add enclosing class references
                    innerClass.accept(new RecursiveASTVisitor<Void>() {
                        @Override
                        public Void visitMethodInvocation(MethodInvocation node) {
                            if (node.getTarget() == null) {
                                IMethodBinding methodBinding = (IMethodBinding) context.getNodeBinding(node);
                                if (methodBinding != null
                                        && methodBinding.getDeclaringClass() == enclosingTypeBinding) {
                                    addEnclosingTypeRef.set(true);
                                    node.setTarget(enclosingTypeRef);
                                }
                            }
                            return super.visitMethodInvocation(node);
                        }

                        @Override
                        public Void visitSimpleIdentifier(SimpleIdentifier node) {
                            if (!(node.getParent() instanceof PropertyAccess)
                                    && !(node.getParent() instanceof PrefixedIdentifier)) {
                                Object binding = context.getNodeBinding(node);
                                if (binding instanceof IVariableBinding) {
                                    IVariableBinding variableBinding = (IVariableBinding) binding;
                                    if (variableBinding.isField()
                                            && variableBinding.getDeclaringClass() == enclosingTypeBinding) {
                                        addEnclosingTypeRef.set(true);
                                        replaceNode(node.getParent(), node,
                                                propertyAccess(enclosingTypeRef, node));
                                    }
                                }
                            }
                            return super.visitSimpleIdentifier(node);
                        }
                    });
                } else {
                    enclosingTypeRef = null;
                }
            }
            // declare referenced final variables XXX
            final String finalName = name;
            anoDeclaration.accept(new ASTVisitor() {
                final Set<org.eclipse.jdt.core.dom.IVariableBinding> addedParameters = Sets.newHashSet();
                final List<FormalParameter> constructorParameters = Lists.newArrayList();
                int index;

                @Override
                public void endVisit(AnonymousClassDeclaration node) {
                    if (!constructorParameters.isEmpty()) {
                        // add parameters to the existing "inner" constructor XXX
                        for (ClassMember classMember : innerClass.getMembers()) {
                            if (classMember instanceof ConstructorDeclaration) {
                                ConstructorDeclaration innerConstructor = (ConstructorDeclaration) classMember;
                                innerConstructor.getParameters().getParameters().addAll(constructorParameters);
                                return;
                            }
                        }
                        // create new "inner" constructor
                        innerClass.getMembers().add(index, constructorDeclaration(identifier(finalName), null,
                                formalParameterList(constructorParameters), null));
                    }
                    super.endVisit(node);
                }

                @Override
                public void endVisit(SimpleName node) {
                    IBinding nameBinding = node.resolveBinding();
                    if (nameBinding instanceof org.eclipse.jdt.core.dom.IVariableBinding) {
                        org.eclipse.jdt.core.dom.IVariableBinding variableBinding = (org.eclipse.jdt.core.dom.IVariableBinding) nameBinding;
                        org.eclipse.jdt.core.dom.MethodDeclaration enclosingMethod = getEnclosingMethod(node);
                        if (!variableBinding.isField() && enclosingMethod != null
                                && variableBinding.getDeclaringMethod() != enclosingMethod.resolveBinding()
                                && addedParameters.add(variableBinding)) {
                            TypeName parameterTypeName = translateTypeName(variableBinding.getType());
                            String parameterName = variableBinding.getName();
                            SimpleIdentifier parameterNameNode = identifier(parameterName);
                            innerClass.getMembers().add(index++, fieldDeclaration(parameterTypeName,
                                    variableDeclaration(parameterNameNode)));
                            constructorParameters.add(fieldFormalParameter(null, null, parameterNameNode));
                            arguments.add(parameterNameNode);
                            context.putReference(parameterNameNode, variableBinding, null);
                        }
                    }
                    super.endVisit(node);
                }

                @Override
                public boolean visit(AnonymousClassDeclaration node) {
                    if (addEnclosingTypeRef.get()) {
                        TypeName parameterTypeName = translateTypeName(enclosingTypeBinding);
                        innerClass.getMembers().add(index++, fieldDeclaration(false, Keyword.FINAL,
                                parameterTypeName, variableDeclaration(enclosingTypeRef)));
                        constructorParameters.add(fieldFormalParameter(null, null, enclosingTypeRef));
                        arguments.add(thisExpression());
                    }
                    return super.visit(node);
                }
            });
        } else {
            innerClass = null;
        }
    }
    InstanceCreationExpression creation = instanceCreationExpression(Keyword.NEW, typeNameNode, null,
            arguments);
    context.putNodeBinding(creation, binding);
    context.putAnonymousDeclaration(creation, innerClass);
    context.getConstructorDescription(binding).instanceCreations.add(creation);
    return done(creation);
}

From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerTest.java

/**
 * It verifies that if bk-client doesn't complete the add-entry in given time out then broker is resilient enought
 * to create new ledger and add entry successfully.
 * //from   w  ww . jav a2 s .c  o m
 * 
 * @throws Exception
 */
@Test(timeOut = 20000)
public void testManagedLedgerWithAddEntryTimeOut() throws Exception {
    ManagedLedgerConfig config = new ManagedLedgerConfig().setAddEntryTimeoutSeconds(1);
    ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("timeout_ledger_test", config);

    BookKeeper bk = mock(BookKeeper.class);
    doNothing().when(bk).asyncCreateLedger(anyInt(), anyInt(), anyInt(), any(), any(), any(), any(), any());

    PulsarMockBookKeeper bkClient = mock(PulsarMockBookKeeper.class);
    ClientConfiguration conf = new ClientConfiguration();
    doReturn(conf).when(bkClient).getConf();
    class MockLedgerHandle extends PulsarMockLedgerHandle {
        public MockLedgerHandle(PulsarMockBookKeeper bk, long id, DigestType digest, byte[] passwd)
                throws GeneralSecurityException {
            super(bk, id, digest, passwd);
        }

        @Override
        public void asyncAddEntry(final byte[] data, final AddCallback cb, final Object ctx) {
            // do nothing
        }

        @Override
        public void asyncClose(org.apache.bookkeeper.client.AsyncCallback.CloseCallback cb, Object ctx) {
            cb.closeComplete(BKException.Code.OK, this, ctx);
        }
    }
    MockLedgerHandle ledgerHandle = mock(MockLedgerHandle.class);
    final String data = "data";
    doNothing().when(ledgerHandle).asyncAddEntry(data.getBytes(), null, null);
    AtomicBoolean addSuccess = new AtomicBoolean();

    setFieldValue(ManagedLedgerImpl.class, ledger, "currentLedger", ledgerHandle);

    final int totalAddEntries = 1;
    CountDownLatch latch = new CountDownLatch(totalAddEntries);
    ledger.asyncAddEntry(data.getBytes(), new AddEntryCallback() {

        @Override
        public void addComplete(Position position, Object ctx) {
            addSuccess.set(true);
            latch.countDown();
        }

        @Override
        public void addFailed(ManagedLedgerException exception, Object ctx) {
            latch.countDown();
        }
    }, null);

    latch.await();

    assertTrue(addSuccess.get());

    setFieldValue(ManagedLedgerImpl.class, ledger, "currentLedger", null);
}

From source file:org.apache.hadoop.hive.metastore.txn.TestTxnHandler.java

@Test
@Ignore/*from  ww  w  .j  a va 2 s  .com*/
public void deadlockDetected() throws Exception {
    LOG.debug("Starting deadlock test");
    Connection conn = txnHandler.getDbConn(Connection.TRANSACTION_SERIALIZABLE);
    Statement stmt = conn.createStatement();
    long now = txnHandler.getDbTime(conn);
    stmt.executeUpdate("insert into TXNS (txn_id, txn_state, txn_started, txn_last_heartbeat, "
            + "txn_user, txn_host) values (1, 'o', " + now + ", " + now + ", 'shagy', " + "'scooby.com')");
    stmt.executeUpdate("insert into HIVE_LOCKS (hl_lock_ext_id, hl_lock_int_id, hl_txnid, "
            + "hl_db, hl_table, hl_partition, hl_lock_state, hl_lock_type, hl_last_heartbeat, "
            + "hl_user, hl_host) values (1, 1, 1, 'mydb', 'mytable', 'mypartition', '" + txnHandler.LOCK_WAITING
            + "', '" + txnHandler.LOCK_EXCLUSIVE + "', " + now + ", 'fred', " + "'scooby.com')");
    conn.commit();
    txnHandler.closeDbConn(conn);

    final AtomicBoolean sawDeadlock = new AtomicBoolean();

    final Connection conn1 = txnHandler.getDbConn(Connection.TRANSACTION_SERIALIZABLE);
    final Connection conn2 = txnHandler.getDbConn(Connection.TRANSACTION_SERIALIZABLE);
    try {

        for (int i = 0; i < 5; i++) {
            Thread t1 = new Thread() {
                @Override
                public void run() {
                    try {
                        try {
                            updateTxns(conn1);
                            updateLocks(conn1);
                            Thread.sleep(1000);
                            conn1.commit();
                            LOG.debug("no exception, no deadlock");
                        } catch (SQLException e) {
                            try {
                                txnHandler.checkRetryable(conn1, e, "thread t1");
                                LOG.debug("Got an exception, but not a deadlock, SQLState is " + e.getSQLState()
                                        + " class of exception is " + e.getClass().getName() + " msg is <"
                                        + e.getMessage() + ">");
                            } catch (TxnHandler.RetryException de) {
                                LOG.debug("Forced a deadlock, SQLState is " + e.getSQLState() + " class of "
                                        + "exception is " + e.getClass().getName() + " msg is <"
                                        + e.getMessage() + ">");
                                sawDeadlock.set(true);
                            }
                        }
                        conn1.rollback();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            };

            Thread t2 = new Thread() {
                @Override
                public void run() {
                    try {
                        try {
                            updateLocks(conn2);
                            updateTxns(conn2);
                            Thread.sleep(1000);
                            conn2.commit();
                            LOG.debug("no exception, no deadlock");
                        } catch (SQLException e) {
                            try {
                                txnHandler.checkRetryable(conn2, e, "thread t2");
                                LOG.debug("Got an exception, but not a deadlock, SQLState is " + e.getSQLState()
                                        + " class of exception is " + e.getClass().getName() + " msg is <"
                                        + e.getMessage() + ">");
                            } catch (TxnHandler.RetryException de) {
                                LOG.debug("Forced a deadlock, SQLState is " + e.getSQLState() + " class of "
                                        + "exception is " + e.getClass().getName() + " msg is <"
                                        + e.getMessage() + ">");
                                sawDeadlock.set(true);
                            }
                        }
                        conn2.rollback();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            };

            t1.start();
            t2.start();
            t1.join();
            t2.join();
            if (sawDeadlock.get())
                break;
        }
        assertTrue(sawDeadlock.get());
    } finally {
        conn1.rollback();
        txnHandler.closeDbConn(conn1);
        conn2.rollback();
        txnHandler.closeDbConn(conn2);
    }
}

From source file:com.netflix.curator.framework.recipes.queue.TestBoundedDistributedQueue.java

@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
@Test//  w  w w  .  j  a  va 2 s . c o m
public void testMulti() throws Exception {
    final String PATH = "/queue";
    final int CLIENT_QTY = 4;
    final int MAX_ITEMS = 10;
    final int ADD_ITEMS = MAX_ITEMS * 100;
    final int SLOP_FACTOR = 2;

    final QueueConsumer<String> consumer = new QueueConsumer<String>() {
        @Override
        public void consumeMessage(String message) throws Exception {
            Thread.sleep(10);
        }

        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
        }
    };

    final Timing timing = new Timing();
    final ExecutorService executor = Executors.newCachedThreadPool();
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executor);

    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            timing.session(), timing.connection(), new RetryOneTime(1));
    try {
        client.start();
        client.create().forPath(PATH);

        final CountDownLatch isWaitingLatch = new CountDownLatch(1);
        final AtomicBoolean isDone = new AtomicBoolean(false);
        final List<Integer> counts = new CopyOnWriteArrayList<Integer>();
        final Object lock = new Object();
        executor.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                Watcher watcher = new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        synchronized (lock) {
                            lock.notifyAll();
                        }
                    }
                };

                while (!Thread.currentThread().isInterrupted() && client.isStarted() && !isDone.get()) {
                    synchronized (lock) {
                        int size = client.getChildren().usingWatcher(watcher).forPath(PATH).size();
                        counts.add(size);
                        isWaitingLatch.countDown();
                        lock.wait();
                    }
                }
                return null;
            }
        });
        isWaitingLatch.await();

        for (int i = 0; i < CLIENT_QTY; ++i) {
            final int index = i;
            completionService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    CuratorFramework client = null;
                    DistributedQueue<String> queue = null;

                    try {
                        client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
                                timing.connection(), new RetryOneTime(1));
                        client.start();
                        queue = QueueBuilder.builder(client, consumer, serializer, PATH).executor(executor)
                                .maxItems(MAX_ITEMS).putInBackground(false).lockPath("/locks").buildQueue();
                        queue.start();

                        for (int i = 0; i < ADD_ITEMS; ++i) {
                            queue.put("" + index + "-" + i);
                        }
                    } finally {
                        IOUtils.closeQuietly(queue);
                        IOUtils.closeQuietly(client);
                    }
                    return null;
                }
            });
        }

        for (int i = 0; i < CLIENT_QTY; ++i) {
            completionService.take().get();
        }

        isDone.set(true);
        synchronized (lock) {
            lock.notifyAll();
        }

        for (int count : counts) {
            Assert.assertTrue(counts.toString(), count <= (MAX_ITEMS * SLOP_FACTOR));
        }
    } finally {
        executor.shutdownNow();
        IOUtils.closeQuietly(client);
    }
}

From source file:com.atlassian.jira.bc.group.TestDefaultGroupService.java

@Test
public void testValidateAddUsersToGroupHappy() {
    final AtomicBoolean validateGroupNamesExistCalled = new AtomicBoolean(false);
    final AtomicBoolean isUserNullCalled = new AtomicBoolean(false);
    final AtomicBoolean isExternalUserManagementEnabledCalled = new AtomicBoolean(false);
    final AtomicBoolean getNonMemberGroupsCalled = new AtomicBoolean(false);
    final AtomicBoolean validateUserIsNotInSelectedGroupsCalled = new AtomicBoolean(false);
    final DefaultGroupService defaultGroupService = new DefaultGroupService(null, null, null, null, null, null,
            null, null, null, null, null, null, null, null) {

        @Override/*w  ww  . j  ava 2  s .  c  o m*/
        boolean validateGroupNamesExist(final Collection groupNames, final ErrorCollection errorCollection,
                final I18nHelper i18n) {
            validateGroupNamesExistCalled.set(true);
            return true;
        }

        @Override
        boolean isUserNull(final User user) {
            isUserNullCalled.set(true);
            return false;
        }

        @Override
        boolean isExternalUserManagementEnabled() {
            isExternalUserManagementEnabledCalled.set(true);
            return false;
        }

        @Override
        List getGroupNamesUserCanSee(final com.atlassian.crowd.embedded.api.User currentUser) {
            getNonMemberGroupsCalled.set(true);
            return EasyList.build("SomeOtherGroup", "SomeGroup");
        }

        @Override
        boolean validateUserIsNotInSelectedGroups(final JiraServiceContext jiraServiceContext,
                final Collection selectedGroupsNames, final User user) {
            validateUserIsNotInSelectedGroupsCalled.set(true);
            return true;
        }

        @Override
        User getUser(final String userName) {
            return null;
        }

        @Override
        boolean userHasAdminPermission(final User user) {
            return true;
        }

        @Override
        boolean groupsHaveGlobalUsePermissions(final Collection /* <String> */ groupNames) {
            return false;
        }
    };
    final SimpleErrorCollection errors = new SimpleErrorCollection();
    final JiraServiceContext jiraServiceContext = getContext(errors);
    assertTrue(defaultGroupService
            .validateAddUsersToGroup(jiraServiceContext, EasyList.build("SomeGroup"), EasyList.build("dude"))
            .isSuccess());
    assertTrue(validateGroupNamesExistCalled.get());
    assertTrue(isUserNullCalled.get());
    assertTrue(isExternalUserManagementEnabledCalled.get());
    assertTrue(getNonMemberGroupsCalled.get());
    assertTrue(validateUserIsNotInSelectedGroupsCalled.get());

}

From source file:com.spectralogic.ds3client.integration.GetJobManagement_Test.java

@Test
public void testReadRetrybugWhenChannelThrowsAccessException() throws IOException, URISyntaxException,
        NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    final String tempPathPrefix = null;
    final Path tempDirectoryPath = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final AtomicBoolean caughtException = new AtomicBoolean(false);

    try {/* w ww . j a va2s  . c  o m*/
        final String DIR_NAME = "largeFiles/";
        final String FILE_NAME = "lesmis-copies.txt";

        final Path objPath = ResourceUtils.loadFileResource(DIR_NAME + FILE_NAME);
        final long bookSize = Files.size(objPath);
        final Ds3Object obj = new Ds3Object(FILE_NAME, bookSize);

        final Ds3ClientShim ds3ClientShim = new Ds3ClientShim((Ds3ClientImpl) client);

        final int maxNumBlockAllocationRetries = 1;
        final int maxNumObjectTransferAttempts = 3;
        final Ds3ClientHelpers ds3ClientHelpers = Ds3ClientHelpers.wrap(ds3ClientShim,
                maxNumBlockAllocationRetries, maxNumObjectTransferAttempts);

        final Ds3ClientHelpers.Job readJob = ds3ClientHelpers.startReadJob(BUCKET_NAME, Arrays.asList(obj));

        final GetJobSpectraS3Response jobSpectraS3Response = ds3ClientShim
                .getJobSpectraS3(new GetJobSpectraS3Request(readJob.getJobId()));

        assertThat(jobSpectraS3Response.getMasterObjectListResult(), is(notNullValue()));

        readJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() {
            @Override
            public SeekableByteChannel buildChannel(final String key) throws IOException {
                throw new AccessControlException(key);
            }
        });
    } catch (final IOException e) {
        caughtException.set(true);
        assertTrue(e.getCause() instanceof AccessControlException);
    } finally {
        FileUtils.deleteDirectory(tempDirectoryPath.toFile());
    }

    assertTrue(caughtException.get());
}

From source file:io.pravega.controller.eventProcessor.impl.SerializedRequestHandlerTest.java

@Test(timeout = 10000)
public void testPostponeEvent() throws InterruptedException, ExecutionException {
    AtomicInteger postponeS1e1Count = new AtomicInteger();
    AtomicInteger postponeS1e2Count = new AtomicInteger();
    AtomicBoolean allowCompletion = new AtomicBoolean(false);

    SerializedRequestHandler<TestEvent> requestHandler = new SerializedRequestHandler<TestEvent>(
            executorService()) {/* w w w.j av  a  2 s .c om*/
        @Override
        public CompletableFuture<Void> processEvent(TestEvent event) {
            if (!event.future.isDone()) {
                return Futures.failedFuture(new TestPostponeException());
            }
            return event.getFuture();
        }

        @Override
        public boolean toPostpone(TestEvent event, long pickupTime, Throwable exception) {

            boolean retval = true;

            if (allowCompletion.get()) {
                if (event.number == 1) {
                    postponeS1e1Count.incrementAndGet();
                    retval = exception instanceof TestPostponeException && postponeS1e1Count.get() < 2;
                }

                if (event.number == 2) {
                    postponeS1e2Count.incrementAndGet();
                    retval = exception instanceof TestPostponeException
                            && (System.currentTimeMillis() - pickupTime < Duration.ofMillis(100).toMillis());
                }
            }

            return retval;
        }
    };

    List<Pair<TestEvent, CompletableFuture<Void>>> stream1Queue = requestHandler
            .getEventQueueForKey(getKeyForStream("scope", "stream1"));
    assertNull(stream1Queue);
    // post 3 work for stream1
    TestEvent s1e1 = new TestEvent("scope", "stream1", 1);
    CompletableFuture<Void> s1p1 = requestHandler.process(s1e1);
    TestEvent s1e2 = new TestEvent("scope", "stream1", 2);
    CompletableFuture<Void> s1p2 = requestHandler.process(s1e2);
    TestEvent s1e3 = new TestEvent("scope", "stream1", 3);
    CompletableFuture<Void> s1p3 = requestHandler.process(s1e3);

    // post events for some more arbitrary streams in background
    AtomicBoolean stop = new AtomicBoolean(false);

    runBackgroundStreamProcessing("stream2", requestHandler, stop);
    runBackgroundStreamProcessing("stream3", requestHandler, stop);
    runBackgroundStreamProcessing("stream4", requestHandler, stop);

    s1e3.complete();
    // verify that s1p3 completes.
    assertTrue(Futures.await(s1p3));
    // verify that s1e1 and s1e2 are still not complete.
    assertTrue(!s1e1.getFuture().isDone());
    assertTrue(!s1p1.isDone());
    assertTrue(!s1e2.getFuture().isDone());
    assertTrue(!s1p2.isDone());

    // Allow completion
    allowCompletion.set(true);

    assertFalse(Futures.await(s1p1));
    assertFalse(Futures.await(s1p2));
    AssertExtensions.assertThrows("", s1p1::join, e -> Exceptions.unwrap(e) instanceof TestPostponeException);
    AssertExtensions.assertThrows("", s1p2::join, e -> Exceptions.unwrap(e) instanceof TestPostponeException);
    assertTrue(postponeS1e1Count.get() == 2);
    assertTrue(postponeS1e2Count.get() > 0);
    stop.set(true);
}