List of usage examples for java.util.concurrent.atomic AtomicBoolean wait
public final void wait() throws InterruptedException
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 . ja 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: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 w w w . j a va 2 s .c om 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:org.apache.blur.shell.QueryCommand.java
private void doItInternal(Blur.Iface client, String[] args, PrintWriter out) throws FinishedException, BlurException, TException { CommandLine commandLine = QueryCommandHelper.parse(args, out, name() + " " + usage()); if (commandLine == null) { return;/* w ww . j av a2s .c o m*/ } BlurQuery blurQuery = QueryCommandHelper.getBlurQuery(commandLine); if (Main.debug) { out.println(blurQuery); } _width = 100; if (commandLine.hasOption(QueryCommandHelper.WIDTH)) { _width = Integer.parseInt(commandLine.getOptionValue(QueryCommandHelper.WIDTH)); } String tablename = args[1]; long s = System.nanoTime(); BlurResults blurResults = client.query(tablename, blurQuery); long e = System.nanoTime(); long timeInNanos = e - s; if (blurResults.getTotalResults() == 0) { out.println("No results found in [" + timeInNanos / 1000000.0 + " ms]."); return; } ConsoleReader reader = getConsoleReader(); if (reader == null) { String description = blurResults.getTotalResults() + " results found in [" + timeInNanos / 1000000.0 + " ms]. " + getFetchMetaData(blurResults); out.println(description); List<BlurResult> results = blurResults.getResults(); for (BlurResult result : results) { print(out, result); } return; } String prompt = reader.getPrompt(); reader.setPrompt(""); final TableDisplay tableDisplay = new TableDisplay(reader); tableDisplay.setDescription(white(blurResults.getTotalResults() + " results found in [" + timeInNanos / 1000000.0 + " ms]. " + getFetchMetaData(blurResults))); tableDisplay.setSeperator(" "); try { final AtomicBoolean viewing = new AtomicBoolean(true); tableDisplay.addKeyHook(new Runnable() { @Override public void run() { synchronized (viewing) { viewing.set(false); viewing.notify(); tableDisplay.setStopReadingInput(true); } } }, 'q'); RenderType type = getRenderRype(blurResults); switch (type) { case ROW_MULTI_FAMILY: renderRowMultiFamily(tableDisplay, blurResults); break; case ROW_SINGLE_FAMILY: renderRowSingleFamily(tableDisplay, blurResults); break; default: break; } while (viewing.get()) { synchronized (viewing) { try { viewing.wait(); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } } } finally { try { tableDisplay.close(); } catch (IOException ex) { if (Main.debug) { ex.printStackTrace(); } } try { Thread.sleep(100); } catch (InterruptedException ex) { if (Main.debug) { ex.printStackTrace(); } } try { reader.setPrompt(""); reader.clearScreen(); } catch (IOException ex) { if (Main.debug) { ex.printStackTrace(); } } out.write("\u001B[0m"); out.flush(); reader.setPrompt(prompt); } }
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 www.ja v a 2s.co 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.hadoop.yarn.client.api.async.impl.TestAMRMClientAsync.java
@SuppressWarnings("unchecked") @Test(timeout = 10000)//from w w w. j a va 2s .c o m 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()); }
From source file:org.apache.zeppelin.python.IPythonClient.java
public ExecuteResponse stream_execute(ExecuteRequest request, final InterpreterOutputStream interpreterOutput) { final ExecuteResponse.Builder finalResponseBuilder = ExecuteResponse.newBuilder() .setStatus(ExecuteStatus.SUCCESS); final AtomicBoolean completedFlag = new AtomicBoolean(false); LOGGER.debug("stream_execute code:\n" + request.getCode()); asyncStub.execute(request, new StreamObserver<ExecuteResponse>() { int index = 0; boolean isPreviousOutputImage = false; @Override// ww w . jav a 2s . c o m public void onNext(ExecuteResponse executeResponse) { if (executeResponse.getType() == OutputType.TEXT) { try { LOGGER.debug("Interpreter Streaming Output: " + executeResponse.getOutput()); if (isPreviousOutputImage) { // add '\n' when switch from image to text interpreterOutput.write("\n%text ".getBytes()); } isPreviousOutputImage = false; interpreterOutput.write(executeResponse.getOutput().getBytes()); interpreterOutput.getInterpreterOutput().flush(); } catch (IOException e) { LOGGER.error("Unexpected IOException", e); } } if (executeResponse.getType() == OutputType.IMAGE) { try { LOGGER.debug("Interpreter Streaming Output: IMAGE_DATA"); if (index != 0) { // add '\n' if this is the not the first element. otherwise it would mix the image // with the text interpreterOutput.write("\n".getBytes()); } interpreterOutput.write(("%img " + executeResponse.getOutput()).getBytes()); interpreterOutput.getInterpreterOutput().flush(); isPreviousOutputImage = true; } catch (IOException e) { LOGGER.error("Unexpected IOException", e); } } if (executeResponse.getStatus() == ExecuteStatus.ERROR) { // set the finalResponse to ERROR if any ERROR happens, otherwise the finalResponse would // be SUCCESS. finalResponseBuilder.setStatus(ExecuteStatus.ERROR); } index++; } @Override public void onError(Throwable throwable) { try { interpreterOutput.getInterpreterOutput().write(ExceptionUtils.getStackTrace(throwable)); interpreterOutput.getInterpreterOutput().flush(); } catch (IOException e) { LOGGER.error("Unexpected IOException", e); } LOGGER.error("Fail to call IPython grpc", throwable); finalResponseBuilder.setStatus(ExecuteStatus.ERROR); completedFlag.set(true); synchronized (completedFlag) { completedFlag.notify(); } } @Override public void onCompleted() { synchronized (completedFlag) { try { LOGGER.debug("stream_execute is completed"); interpreterOutput.getInterpreterOutput().flush(); } catch (IOException e) { LOGGER.error("Unexpected IOException", e); } completedFlag.set(true); completedFlag.notify(); } } }); synchronized (completedFlag) { if (!completedFlag.get()) { try { completedFlag.wait(); } catch (InterruptedException e) { LOGGER.error("Unexpected Interruption", e); } } } return finalResponseBuilder.build(); }