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

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

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native void notifyAll();

Source Link

Document

Wakes up all threads that are waiting on this object's monitor.

Usage

From source file:com.alibaba.wasp.executor.TestExecutorService.java

@Test
public void testExecutorService() throws Exception {
    int maxThreads = 5;
    int maxTries = 10;
    int sleepInterval = 10;

    Server mockedServer = mock(Server.class);
    when(mockedServer.getConfiguration()).thenReturn(conf);

    // Start an executor service pool with max 5 threads
    ExecutorService executorService = new ExecutorService("unit_test");
    executorService.startExecutorService(ExecutorType.MASTER_SERVER_OPERATIONS, maxThreads);

    Executor executor = executorService.getExecutor(ExecutorType.MASTER_SERVER_OPERATIONS);
    ThreadPoolExecutor pool = executor.threadPoolExecutor;

    // Assert no threads yet
    assertEquals(0, pool.getPoolSize());

    AtomicBoolean lock = new AtomicBoolean(true);
    AtomicInteger counter = new AtomicInteger(0);

    // Submit maxThreads executors.
    for (int i = 0; i < maxThreads; i++) {
        executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter));
    }//from   ww  w.  j a va  2s .c  o m

    // The TestEventHandler will increment counter when it starts.
    int tries = 0;
    while (counter.get() < maxThreads && tries < maxTries) {
        LOG.info("Waiting for all event handlers to start...");
        Thread.sleep(sleepInterval);
        tries++;
    }

    // Assert that pool is at max threads.
    assertEquals(maxThreads, counter.get());
    assertEquals(maxThreads, pool.getPoolSize());

    ExecutorStatus status = executor.getStatus();
    assertTrue(status.queuedEvents.isEmpty());
    assertEquals(5, status.running.size());
    checkStatusDump(status);

    // Now interrupt the running Executor
    synchronized (lock) {
        lock.set(false);
        lock.notifyAll();
    }

    // Executor increments counter again on way out so.... test that happened.
    while (counter.get() < (maxThreads * 2) && tries < maxTries) {
        System.out.println("Waiting for all event handlers to finish...");
        Thread.sleep(sleepInterval);
        tries++;
    }

    assertEquals(maxThreads * 2, counter.get());
    assertEquals(maxThreads, pool.getPoolSize());

    // Add more than the number of threads items.
    // Make sure we don't get RejectedExecutionException.
    for (int i = 0; i < (2 * maxThreads); i++) {
        executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter));
    }
    // Now interrupt the running Executor
    synchronized (lock) {
        lock.set(false);
        lock.notifyAll();
    }

    // Make sure threads are still around even after their timetolive expires.
    Thread.sleep(ExecutorService.Executor.keepAliveTimeInMillis * 2);
    assertEquals(maxThreads, pool.getPoolSize());

    executorService.shutdown();

    assertEquals(0, executorService.getAllExecutorStatuses().size());

    // Test that submit doesn't throw NPEs
    executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter));
}

From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java

private String launchProcess(final Settings settings, final PortGroup portGroup) {
    final AtomicBoolean ready = new AtomicBoolean();
    final AtomicReference<String> logPrefix = new AtomicReference<String>("");
    new Thread(new Runnable() {
        @Override//from   www . j  a v a2s  . co  m
        public void run() {
            List<String> myArgs = new ArrayList<String>();
            myArgs.add(settings.javaBinary() == null ? JAVA_BIN : settings.javaBinary());
            myArgs.addAll(inheritedArgs);
            if (!settings.customClasspath()) {
                myArgs.addAll(classpathArgs.get());
            }
            if (settings.javaExportModules()) {
                myArgs.add("-XaddExports:javafx.web/com.sun.webkit.network=ALL-UNNAMED");
                myArgs.add("-XaddExports:javafx.web/com.sun.webkit.network.about=ALL-UNNAMED");
                myArgs.add("-XaddExports:javafx.web/com.sun.webkit.network.data=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.http=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.https=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.file=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.ftp=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.jar=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.mailto=ALL-UNNAMED");
                myArgs.add("-XaddExports:javafx.graphics/com.sun.glass.ui=ALL-UNNAMED");
                myArgs.add("-XaddExports:javafx.web/com.sun.javafx.webkit=ALL-UNNAMED");
                myArgs.add("-XaddExports:javafx.web/com.sun.webkit=ALL-UNNAMED");
            }
            myArgs.add("-Djava.io.tmpdir=" + tmpDir.getAbsolutePath());
            myArgs.add("-Djava.rmi.server.hostname=" + settings.host());
            myArgs.addAll(settings.javaOptions());
            myArgs.add(JBrowserDriverServer.class.getName());
            myArgs.add(Long.toString(portGroup.child));
            myArgs.add(Long.toString(portGroup.parent));
            myArgs.add(Long.toString(portGroup.parentAlt));
            try {
                new ProcessExecutor().addListener(new ProcessListener() {
                    @Override
                    public void afterStart(Process proc, ProcessExecutor executor) {
                        process.set(proc);
                    }
                }).redirectOutput(new LogOutputStream() {
                    boolean done = false;

                    @Override
                    protected void processLine(String line) {
                        if (line != null && !line.isEmpty()) {
                            if (!done) {
                                synchronized (ready) {
                                    if (line.startsWith("ready on ports ")) {
                                        String[] parts = line.substring("ready on ports ".length()).split("/");
                                        actualPortGroup.set(new PortGroup(Integer.parseInt(parts[0]),
                                                Integer.parseInt(parts[1]), Integer.parseInt(parts[2])));
                                        logPrefix.set(new StringBuilder().append("[Instance ")
                                                .append(sessionIdCounter.incrementAndGet()).append("][Port ")
                                                .append(actualPortGroup.get().child).append("]").toString());
                                        ready.set(true);
                                        ready.notifyAll();
                                        done = true;
                                    } else {
                                        log(settings.logger(), logPrefix.get(), line);
                                    }
                                }
                            } else {
                                log(settings.logger(), logPrefix.get(), line);
                            }
                        }
                    }
                }).redirectError(new LogOutputStream() {
                    @Override
                    protected void processLine(String line) {
                        log(settings.logger(), logPrefix.get(), line);
                    }
                }).destroyOnExit().command(myArgs).execute();
            } catch (Throwable t) {
                Util.handleException(t);
            }
            synchronized (ready) {
                ready.set(true);
                ready.notifyAll();
            }
        }
    }).start();
    synchronized (ready) {
        while (!ready.get()) {
            try {
                ready.wait();
                break;
            } catch (InterruptedException e) {
            }
        }
    }
    return logPrefix.get();
}

From source file:com.gemstone.gemfire.internal.cache.OplogJUnitTest.java

/**
 * tests directory stats are correctly updated in case of single directory
 * (for bug 37531)//from  w w  w .j a v  a  2  s  . c  o  m
 */
@Test
public void testPersist1DirStats() {
    final AtomicBoolean freezeRoller = new AtomicBoolean();
    CacheObserver old = CacheObserverHolder.setInstance(new CacheObserverAdapter() {
        private volatile boolean didBeforeCall = false;

        @Override
        public void beforeGoingToCompact() {
            this.didBeforeCall = true;
            synchronized (freezeRoller) {
                if (!assertDone) {
                    try {
                        // Here, we are not allowing the Roller thread to roll the old oplog into htree
                        while (!freezeRoller.get()) {
                            freezeRoller.wait();
                        }
                        freezeRoller.set(false);
                    } catch (InterruptedException e) {
                        fail("interrupted");
                    }
                }
            }
        }

        @Override
        public void afterHavingCompacted() {
            if (this.didBeforeCall) {
                this.didBeforeCall = false;
                LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false;
                //assertTrue("Assert failure for DSpaceUsage in afterHavingCompacted ", diskSpaceUsageStats() == calculatedDiskSpaceUsageStats());
                // what is the point of this assert?
                checkDiskStats();
            }
        }
    });
    try {
        final int MAX_OPLOG_SIZE = 500;
        diskProps.setMaxOplogSize(MAX_OPLOG_SIZE);
        diskProps.setPersistBackup(true);
        diskProps.setRolling(true);
        diskProps.setSynchronous(true);
        diskProps.setOverflow(false);
        diskProps.setDiskDirsAndSizes(new File[] { dirs[0] }, new int[] { 4000 });
        final byte[] val = new byte[200];
        region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskProps, Scope.LOCAL);
        LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
        region.put("key1", val);
        // Disk space should have changed due to 1 put
        //assertTrue("stats did not increase after put 1 ", diskSpaceUsageStats() == calculatedDiskSpaceUsageStats());
        checkDiskStats();
        region.put("key2", val);
        //assertTrue("stats did not increase after put 2", diskSpaceUsageStats() == calculatedDiskSpaceUsageStats());
        checkDiskStats();
        // This put will cause a switch as max-oplog size (500) will be exceeded (600)
        region.put("key3", val);
        synchronized (freezeRoller) {
            //assertTrue("current disk space usage with Roller thread in wait and put key3 done is incorrect " +  diskSpaceUsageStats() + " " + calculatedDiskSpaceUsageStats(), diskSpaceUsageStats()== calculatedDiskSpaceUsageStats());
            checkDiskStats();
            assertDone = true;
            freezeRoller.set(true);
            freezeRoller.notifyAll();
        }

        region.close();
        closeDown();
        //    Stop rolling to get accurate estimates:
        diskProps.setRolling(false);

        region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskProps, Scope.LOCAL);

        // On recreating the region after closing, old Oplog file gets rolled into htree
        // "Disk space usage zero when region recreated"
        checkDiskStats();
        region.put("key4", val);
        //assertTrue("stats did not increase after put 4", diskSpaceUsageStats() == calculatedDiskSpaceUsageStats());
        checkDiskStats();
        region.put("key5", val);
        //assertTrue("stats did not increase after put 5", diskSpaceUsageStats() == calculatedDiskSpaceUsageStats());
        checkDiskStats();
        assertDone = false;
        LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
        region.put("key6", val);
        // again we expect a switch in oplog here
        synchronized (freezeRoller) {
            //assertTrue("current disk space usage with Roller thread in wait and put key6 done is incorrect", diskSpaceUsageStats()== calculatedDiskSpaceUsageStats());
            checkDiskStats();
            assertDone = true;
            freezeRoller.set(true);
            freezeRoller.notifyAll();
        }
        region.close();
    } catch (Exception e) {
        e.printStackTrace();
        fail("Test failed due to exception" + e);
    } finally {
        LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false;
        CacheObserverHolder.setInstance(old);
        synchronized (freezeRoller) {
            assertDone = true;
            freezeRoller.set(true);
            freezeRoller.notifyAll();
        }
    }
}

From source file:org.apache.geode.internal.cache.OplogJUnitTest.java

/**
 * tests directory stats are correctly updated in case of single directory (for bug 37531)
 *//*from  w w w.  jav  a 2  s.c  om*/
@Test
public void testPersist1DirStats() {
    final AtomicBoolean freezeRoller = new AtomicBoolean();
    CacheObserver old = CacheObserverHolder.setInstance(new CacheObserverAdapter() {
        private volatile boolean didBeforeCall = false;

        @Override
        public void beforeGoingToCompact() {
            this.didBeforeCall = true;
            synchronized (freezeRoller) {
                if (!assertDone) {
                    try {
                        // Here, we are not allowing the Roller thread to roll the old oplog into htree
                        while (!freezeRoller.get()) {
                            freezeRoller.wait();
                        }
                        freezeRoller.set(false);
                    } catch (InterruptedException e) {
                        fail("interrupted");
                    }
                }
            }
        }

        @Override
        public void afterHavingCompacted() {
            if (this.didBeforeCall) {
                this.didBeforeCall = false;
                LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false;
                // assertTrue("Assert failure for DSpaceUsage in afterHavingCompacted ",
                // diskSpaceUsageStats() == calculatedDiskSpaceUsageStats());
                // what is the point of this assert?
                checkDiskStats();
            }
        }
    });
    try {
        final int MAX_OPLOG_SIZE = 500;
        diskProps.setMaxOplogSize(MAX_OPLOG_SIZE);
        diskProps.setPersistBackup(true);
        diskProps.setRolling(true);
        diskProps.setSynchronous(true);
        diskProps.setOverflow(false);
        diskProps.setDiskDirsAndSizes(new File[] { dirs[0] }, new int[] { 4000 });
        final byte[] val = new byte[200];
        region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskProps, Scope.LOCAL);
        LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
        region.put("key1", val);
        // Disk space should have changed due to 1 put
        // assertTrue("stats did not increase after put 1 ", diskSpaceUsageStats() ==
        // calculatedDiskSpaceUsageStats());
        checkDiskStats();
        region.put("key2", val);
        // assertTrue("stats did not increase after put 2", diskSpaceUsageStats() ==
        // calculatedDiskSpaceUsageStats());
        checkDiskStats();
        // This put will cause a switch as max-oplog size (500) will be exceeded (600)
        region.put("key3", val);
        synchronized (freezeRoller) {
            // assertTrue("current disk space usage with Roller thread in wait and put key3 done is
            // incorrect " + diskSpaceUsageStats() + " " + calculatedDiskSpaceUsageStats(),
            // diskSpaceUsageStats()== calculatedDiskSpaceUsageStats());
            checkDiskStats();
            assertDone = true;
            freezeRoller.set(true);
            freezeRoller.notifyAll();
        }

        region.close();
        closeDown();
        // Stop rolling to get accurate estimates:
        diskProps.setRolling(false);

        region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskProps, Scope.LOCAL);

        // On recreating the region after closing, old Oplog file gets rolled into htree
        // "Disk space usage zero when region recreated"
        checkDiskStats();
        region.put("key4", val);
        // assertTrue("stats did not increase after put 4", diskSpaceUsageStats() ==
        // calculatedDiskSpaceUsageStats());
        checkDiskStats();
        region.put("key5", val);
        // assertTrue("stats did not increase after put 5", diskSpaceUsageStats() ==
        // calculatedDiskSpaceUsageStats());
        checkDiskStats();
        assertDone = false;
        LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
        region.put("key6", val);
        // again we expect a switch in oplog here
        synchronized (freezeRoller) {
            // assertTrue("current disk space usage with Roller thread in wait and put key6 done is
            // incorrect", diskSpaceUsageStats()== calculatedDiskSpaceUsageStats());
            checkDiskStats();
            assertDone = true;
            freezeRoller.set(true);
            freezeRoller.notifyAll();
        }
        region.close();
    } catch (Exception e) {
        e.printStackTrace();
        fail("Test failed due to exception" + e);
    } finally {
        LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false;
        CacheObserverHolder.setInstance(old);
        synchronized (freezeRoller) {
            assertDone = true;
            freezeRoller.set(true);
            freezeRoller.notifyAll();
        }
    }
}

From source file:org.apache.hadoop.hbase.executor.TestExecutorService.java

@Test
public void testExecutorService() throws Exception {
    int maxThreads = 5;
    int maxTries = 10;
    int sleepInterval = 10;

    Server mockedServer = mock(Server.class);
    when(mockedServer.getConfiguration()).thenReturn(HBaseConfiguration.create());

    // Start an executor service pool with max 5 threads
    ExecutorService executorService = new ExecutorService("unit_test");
    executorService.startExecutorService(ExecutorType.MASTER_SERVER_OPERATIONS, maxThreads);

    Executor executor = executorService.getExecutor(ExecutorType.MASTER_SERVER_OPERATIONS);
    ThreadPoolExecutor pool = executor.threadPoolExecutor;

    // Assert no threads yet
    assertEquals(0, pool.getPoolSize());

    AtomicBoolean lock = new AtomicBoolean(true);
    AtomicInteger counter = new AtomicInteger(0);

    // Submit maxThreads executors.
    for (int i = 0; i < maxThreads; i++) {
        executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter));
    }/* ww w.  jav  a2  s .  c om*/

    // The TestEventHandler will increment counter when it starts.
    int tries = 0;
    while (counter.get() < maxThreads && tries < maxTries) {
        LOG.info("Waiting for all event handlers to start...");
        Thread.sleep(sleepInterval);
        tries++;
    }

    // Assert that pool is at max threads.
    assertEquals(maxThreads, counter.get());
    assertEquals(maxThreads, pool.getPoolSize());

    ExecutorStatus status = executor.getStatus();
    assertTrue(status.queuedEvents.isEmpty());
    assertEquals(5, status.running.size());
    checkStatusDump(status);

    // Now interrupt the running Executor
    synchronized (lock) {
        lock.set(false);
        lock.notifyAll();
    }

    // Executor increments counter again on way out so.... test that happened.
    while (counter.get() < (maxThreads * 2) && tries < maxTries) {
        System.out.println("Waiting for all event handlers to finish...");
        Thread.sleep(sleepInterval);
        tries++;
    }

    assertEquals(maxThreads * 2, counter.get());
    assertEquals(maxThreads, pool.getPoolSize());

    // Add more than the number of threads items.
    // Make sure we don't get RejectedExecutionException.
    for (int i = 0; i < (2 * maxThreads); i++) {
        executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter));
    }
    // Now interrupt the running Executor
    synchronized (lock) {
        lock.set(false);
        lock.notifyAll();
    }

    // Make sure threads are still around even after their timetolive expires.
    Thread.sleep(ExecutorService.Executor.keepAliveTimeInMillis * 2);
    assertEquals(maxThreads, pool.getPoolSize());

    executorService.shutdown();

    assertEquals(0, executorService.getAllExecutorStatuses().size());

    // Test that submit doesn't throw NPEs
    executorService.submit(new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter));
}

From source file:org.apache.hadoop.yarn.client.api.async.impl.TestAMRMClientAsync.java

@SuppressWarnings("unchecked")
@Test(timeout = 10000)/*from w ww.  j  a  va 2s .com*/
public void testAMRMClientAsync() throws Exception {
    Configuration conf = new Configuration();
    final AtomicBoolean heartbeatBlock = new AtomicBoolean(true);
    List<ContainerStatus> completed1 = Arrays
            .asList(ContainerStatus.newInstance(newContainerId(0, 0, 0, 0), ContainerState.COMPLETE, "", 0));
    List<Container> containers = Arrays.asList(Container.newInstance(null, null, null, null, null, null));
    final AllocateResponse response1 = createAllocateResponse(new ArrayList<ContainerStatus>(), containers,
            null);
    final AllocateResponse response2 = createAllocateResponse(completed1, new ArrayList<Container>(), null);
    final AllocateResponse response3 = createAllocateResponse(new ArrayList<ContainerStatus>(),
            new ArrayList<Container>(), containers, containers, null);
    final AllocateResponse emptyResponse = createAllocateResponse(new ArrayList<ContainerStatus>(),
            new ArrayList<Container>(), null);

    TestCallbackHandler callbackHandler = new TestCallbackHandler();
    final AMRMClient<ContainerRequest> client = mock(AMRMClientImpl.class);
    final AtomicInteger secondHeartbeatSync = new AtomicInteger(0);
    when(client.allocate(anyFloat())).thenReturn(response1).thenAnswer(new Answer<AllocateResponse>() {
        @Override
        public AllocateResponse answer(InvocationOnMock invocation) throws Throwable {
            secondHeartbeatSync.incrementAndGet();
            while (heartbeatBlock.get()) {
                synchronized (heartbeatBlock) {
                    heartbeatBlock.wait();
                }
            }
            secondHeartbeatSync.incrementAndGet();
            return response2;
        }
    }).thenReturn(response3).thenReturn(emptyResponse);
    when(client.registerApplicationMaster(anyString(), anyInt(), anyString())).thenReturn(null);
    when(client.getAvailableResources()).thenAnswer(new Answer<Resource>() {
        @Override
        public Resource answer(InvocationOnMock invocation) throws Throwable {
            // take client lock to simulate behavior of real impl
            synchronized (client) {
                Thread.sleep(10);
            }
            return null;
        }
    });

    AMRMClientAsync<ContainerRequest> asyncClient = AMRMClientAsync.createAMRMClientAsync(client, 20,
            callbackHandler);
    asyncClient.init(conf);
    asyncClient.start();
    asyncClient.registerApplicationMaster("localhost", 1234, null);

    // while the CallbackHandler will still only be processing the first response,
    // heartbeater thread should still be sending heartbeats.
    // To test this, wait for the second heartbeat to be received. 
    while (secondHeartbeatSync.get() < 1) {
        Thread.sleep(10);
    }

    // heartbeat will be blocked. make sure we can call client methods at this
    // time. Checks that heartbeat is not holding onto client lock
    assert (secondHeartbeatSync.get() < 2);
    asyncClient.getAvailableResources();
    // method returned. now unblock heartbeat
    assert (secondHeartbeatSync.get() < 2);
    synchronized (heartbeatBlock) {
        heartbeatBlock.set(false);
        heartbeatBlock.notifyAll();
    }

    // allocated containers should come before completed containers
    Assert.assertEquals(null, callbackHandler.takeCompletedContainers());

    // wait for the allocated containers from the first heartbeat's response
    while (callbackHandler.takeAllocatedContainers() == null) {
        Assert.assertEquals(null, callbackHandler.takeCompletedContainers());
        Thread.sleep(10);
    }

    // wait for the completed containers from the second heartbeat's response
    while (callbackHandler.takeCompletedContainers() == null) {
        Thread.sleep(10);
    }

    // wait for the changed containers from the thrid heartbeat's response
    while (callbackHandler.takeChangedContainers() == null) {
        Thread.sleep(10);
    }

    asyncClient.stop();

    Assert.assertEquals(null, callbackHandler.takeAllocatedContainers());
    Assert.assertEquals(null, callbackHandler.takeCompletedContainers());
    Assert.assertEquals(null, callbackHandler.takeChangedContainers());
}