List of usage examples for java.util.concurrent CountDownLatch countDown
public void countDown()
From source file:com.googlecode.ehcache.annotations.integration.SelfPopulatingMethodTest.java
/** * Verify that setting selfPopulating=true will guarantee only 1 invocation * of the cached method.//w w w . j a v a2 s .c o m * * @throws Exception */ @Test //(timeout=1000) public void testSelfPopulatingTrue() throws Exception { final CountDownLatch threadRunningLatch = new CountDownLatch(6); final CountDownLatch proceedLatch = new CountDownLatch(1); this.selfPopulatingTestInterface.setThreadRunningLatch(threadRunningLatch); this.selfPopulatingTestInterface.setProccedLatch(proceedLatch); Assert.assertEquals(0, this.selfPopulatingTestInterface.getBlockingAInvocationCount()); Assert.assertEquals(0, this.selfPopulatingTestInterface.getBlockingBInvocationCount()); final ThreadGroupRunner threadGroup = new ThreadGroupRunner("testSelfPopulatingTrue-", true); threadGroup.addTask(2, new Runnable() { public void run() { threadRunningLatch.countDown(); logger.trace("Calling blockingA(test2)"); selfPopulatingTestInterface.blockingA("test2"); } }); threadGroup.addTask(2, new Runnable() { public void run() { threadRunningLatch.countDown(); logger.trace("Calling blockingB(test2)"); selfPopulatingTestInterface.blockingB("test2"); } }); threadGroup.start(); // wait for both threads to get going logger.trace("Waiting for threads to start"); threadRunningLatch.await(); // Let both threads complete logger.trace("Signal threads to proceed"); proceedLatch.countDown(); logger.trace("Waiting for threads to complete"); threadGroup.join(); // verify only 1 call between method A and method B Assert.assertEquals(1, this.selfPopulatingTestInterface.getBlockingAInvocationCount()); Assert.assertEquals(1, this.selfPopulatingTestInterface.getBlockingBInvocationCount()); }
From source file:com.microsoft.office.integration.test.MessagesAsyncTestCase.java
private void updateAndCheck() throws Exception { final String content = "updated body text"; ItemBody newBody = new ItemBody(); newBody.setContent(content);//from w ww.j a v a 2 s . c om newBody.setContentType(BodyType.Text); message.setBody(newBody); final CountDownLatch cdl = new CountDownLatch(1); Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() { public void onFailure(Throwable t) { reportError(t); cdl.countDown(); } public void onSuccess(Void result) { assertEquals(BodyType.Text, MessagesAsyncTestCase.this.message.getBody().getContentType()); assertEquals(content, MessagesAsyncTestCase.this.message.getBody().getContent()); // ensure that changes were pushed to endpoint Futures.addCallback(Me.getMessages().getAsync(MessagesAsyncTestCase.this.message.getId()), new FutureCallback<IMessage>() { public void onFailure(Throwable t) { reportError(t); cdl.countDown(); } public void onSuccess(IMessage result) { try { MessagesAsyncTestCase.this.message = result; assertEquals(BodyType.Text, MessagesAsyncTestCase.this.message.getBody().getContentType()); assertEquals(content, MessagesAsyncTestCase.this.message.getBody().getContent()); } catch (Throwable t) { reportError(t); } cdl.countDown(); } }); } }); cdl.await(); }
From source file:com.microsoft.office.core.MessagesAsyncTestCase.java
private void updateAndCheck() throws Exception { final String content = "updated body text"; ItemBody newBody = new ItemBody(); newBody.setContent(content);/*from ww w . jav a 2 s .c o m*/ newBody.setContentType(BodyType.Text); message.setBody(newBody); final CountDownLatch cdl = new CountDownLatch(1); Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() { @Override public void onFailure(Throwable t) { reportError(t); cdl.countDown(); } @Override public void onSuccess(Void result) { assertEquals(BodyType.Text, MessagesAsyncTestCase.this.message.getBody().getContentType()); assertEquals(content, MessagesAsyncTestCase.this.message.getBody().getContent()); // ensure that changes were pushed to endpoint Futures.addCallback(Me.getMessages().getAsync(MessagesAsyncTestCase.this.message.getId()), new FutureCallback<IMessage>() { @Override public void onFailure(Throwable t) { reportError(t); cdl.countDown(); } @Override public void onSuccess(IMessage result) { try { MessagesAsyncTestCase.this.message = result; assertEquals(BodyType.Text, MessagesAsyncTestCase.this.message.getBody().getContentType()); assertEquals(content, MessagesAsyncTestCase.this.message.getBody().getContent()); } catch (Throwable t) { reportError(t); } cdl.countDown(); } }); } }); cdl.await(); }
From source file:com.microsoft.office.core.MessagesAsyncTestCase.java
private void createAndCheck() throws Exception { final CountDownLatch cdl = new CountDownLatch(1); prepareMessage();// ww w . ja v a 2 s. c o m Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() { @Override public void onFailure(Throwable t) { reportError(t); cdl.countDown(); } @Override public void onSuccess(Void result) { try { assertTrue(StringUtils.isNotEmpty(MessagesAsyncTestCase.this.message.getId())); } catch (Throwable t) { reportError(t); } cdl.countDown(); } }); cdl.await(); }
From source file:org.wisdom.framework.vertx.FileUploadTest.java
@Test public void testFileUploadOfSmallFilesOnDisk() throws InterruptedException, IOException { // Prepare the configuration ApplicationConfiguration configuration = mock(ApplicationConfiguration.class); when(configuration.getIntegerWithDefault(eq("vertx.http.port"), anyInt())).thenReturn(0); when(configuration.getIntegerWithDefault(eq("vertx.https.port"), anyInt())).thenReturn(-1); when(configuration.getIntegerWithDefault("vertx.acceptBacklog", -1)).thenReturn(-1); when(configuration.getIntegerWithDefault("vertx.receiveBufferSize", -1)).thenReturn(-1); when(configuration.getIntegerWithDefault("vertx.sendBufferSize", -1)).thenReturn(-1); when(configuration.getIntegerWithDefault("request.body.max.size", 100 * 1024)).thenReturn(100 * 1024); when(configuration.getStringArray("wisdom.websocket.subprotocols")).thenReturn(new String[0]); when(configuration.getStringArray("vertx.websocket-subprotocols")).thenReturn(new String[0]); // Reduce it to force disk storage when(configuration.getLongWithDefault("http.upload.disk.threshold", DiskFileUpload.MINSIZE)) .thenReturn(1024l);/* w ww . j a va2 s .co m*/ when(configuration.getLongWithDefault("http.upload.max", -1l)).thenReturn(-1l); // Prepare the router with a controller Controller controller = new DefaultController() { @SuppressWarnings("unused") public Result index() throws IOException { FileItem item = context().file("upload"); if (item.isInMemory()) { return badRequest("on disk expected"); } if (!item.name().equals("my-file.dat")) { return badRequest("broken name"); } if (item.size() != 2048) { return badRequest("broken file"); } if (!context().form().get("comment").get(0).equals("my description")) { return badRequest("broken form"); } final File file = item.toFile(); if (!file.exists() && file.length() != 2048) { return badRequest("broken file to file handling"); } return ok(item.stream()).as(MimeTypes.BINARY); } }; Router router = mock(Router.class); Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "index"); when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route); ContentEngine contentEngine = getMockContentEngine(); // Configure the server. server = new WisdomVertxServer(); server.accessor = new ServiceAccessor(null, configuration, router, contentEngine, executor, null, Collections.<ExceptionMapper>emptyList()); server.vertx = vertx; server.configuration = configuration; server.start(); VertxHttpServerTest.waitForStart(server); // Now start bunch of clients CountDownLatch startSignal = new CountDownLatch(1); CountDownLatch doneSignal = new CountDownLatch(NUMBER_OF_CLIENTS); int port = server.httpPort(); for (int i = 1; i < NUMBER_OF_CLIENTS + 1; ++i) { clients.submit(new Client(startSignal, doneSignal, port, i, 2048)); } startSignal.countDown(); // let all threads proceed if (!doneSignal.await(120, TimeUnit.SECONDS)) { // wait for all to finish Assert.fail("testFileUploadOfSmallFilesOnDisk - Did not server all requests in time"); } assertThat(failure).isEmpty(); assertThat(success).hasSize(NUMBER_OF_CLIENTS); }
From source file:com.microsoft.office.integration.test.MessagesAsyncTestCase.java
private void createAndCheck() throws Exception { final CountDownLatch cdl = new CountDownLatch(1); prepareMessage();//from www . ja v a2 s . c o m Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() { public void onFailure(Throwable t) { reportError(t); cdl.countDown(); } public void onSuccess(Void result) { try { assertTrue(StringUtils.isNotEmpty(MessagesAsyncTestCase.this.message.getId())); } catch (Throwable t) { reportError(t); } cdl.countDown(); } }); cdl.await(); }
From source file:com.microsoft.office.integration.test.FoldersAsyncTestCase.java
public void testMoveAndCopy() { final String name = "move and copy test" + (int) (Math.random() * 1000000); counter = new CountDownLatch(1); try {//from ww w . j ava2 s . c om Futures.addCallback(Me.getRootFolderAsync().get().getChildFoldersAsync(), new FutureCallback<IFolders>() { public void onFailure(Throwable t) { reportError(t); counter.countDown(); } public void onSuccess(IFolders result) { try { FoldersAsyncTestCase.this.folder = result.newFolder(); FoldersAsyncTestCase.this.folder.setDisplayName(name); FoldersAsyncTestCase.this.folder = FoldersAsyncTestCase.this.folder .moveAsync(Me.getDraftsAsync().get().getId()).get(); final CountDownLatch cdl = new CountDownLatch(1); Futures.addCallback( FoldersAsyncTestCase.this.folder.copyAsync(Me.getRootFolder().getId()), new FutureCallback<IFolder>() { public void onFailure(Throwable t) { reportError(t); cdl.countDown(); } public void onSuccess(IFolder copied) { try { Me.getFolders() .delete(FoldersAsyncTestCase.this.folder.getId()); if (copied != null) { Me.getFolders().delete(copied.getId()); } Me.flush(); } catch (Throwable t) { reportError(t); } cdl.countDown(); } }); cdl.await(); } catch (Throwable t) { reportError(t); } counter.countDown(); } }); try { if (!counter.await(60000, TimeUnit.MILLISECONDS)) { fail("testMoveAndCopy() timed out"); } } catch (InterruptedException e) { fail("testMoveAndCopy() has been interrupted"); } } catch (Exception e) { reportError(e); } }
From source file:com.netflix.curator.framework.imps.TestFailedDeleteManager.java
@Test public void testLostSession() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); try {//from w w w. j ava2 s.c om client.start(); client.create().forPath("/test-me"); final CountDownLatch latch = new CountDownLatch(1); final Semaphore semaphore = new Semaphore(0); ConnectionStateListener listener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) { semaphore.release(); } else if (newState == ConnectionState.RECONNECTED) { latch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); server.stop(); Assert.assertTrue(timing.acquireSemaphore(semaphore)); try { client.delete().guaranteed().forPath("/test-me"); Assert.fail(); } catch (KeeperException.ConnectionLossException e) { // expected } Assert.assertTrue(timing.acquireSemaphore(semaphore)); timing.sleepABit(); server = new TestingServer(server.getPort(), server.getTempDirectory()); Assert.assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/test-me")); } finally { IOUtils.closeQuietly(client); } }
From source file:io.nats.client.ITClusterTest.java
@Test public void testProperFalloutAfterMaxAttempts() throws Exception { Options opts = new Options.Builder(defaultOptions()).dontRandomize().maxReconnect(5) .reconnectWait(25, TimeUnit.MILLISECONDS).build(); opts.servers = Nats.processUrlArray(testServers); final CountDownLatch dcLatch = new CountDownLatch(1); opts.disconnectedCb = new DisconnectedCallback() { public void onDisconnect(ConnectionEvent event) { dcLatch.countDown(); }//from w w w .j a v a 2 s . c o m }; final AtomicBoolean closedCbCalled = new AtomicBoolean(false); final CountDownLatch ccLatch = new CountDownLatch(1); opts.closedCb = new ClosedCallback() { public void onClose(ConnectionEvent event) { closedCbCalled.set(true); ccLatch.countDown(); } }; try (NatsServer s1 = runServerOnPort(1222)) { try (Connection c = opts.connect()) { s1.shutdown(); // wait for disconnect assertTrue("Did not receive a disconnect callback message", await(dcLatch, 2, TimeUnit.SECONDS)); // Wait for ClosedCB assertTrue("Did not receive a closed callback message", await(ccLatch, 2, TimeUnit.SECONDS)); // Make sure we are not still reconnecting. assertTrue("Closed CB was not triggered, should have been.", closedCbCalled.get()); // Expect connection to be closed... assertTrue("Wrong status: " + c.getState(), c.isClosed()); } } }
From source file:com.alibaba.druid.DBCPTest.java
public void test_max() throws Exception { Class.forName("com.alibaba.druid.mock.MockDriver"); final BasicDataSource dataSource = new BasicDataSource(); // final DruidDataSource dataSource = new DruidDataSource(); dataSource.setInitialSize(3);//from w w w .j ava2 s.c om dataSource.setMaxActive(20); dataSource.setMaxIdle(20); dataSource.setDriverClassName("com.alibaba.druid.mock.MockDriver"); dataSource.setUrl("jdbc:mock:xxx"); final int THREAD_COUNT = 200; final CountDownLatch endLatch = new CountDownLatch(THREAD_COUNT); final CountDownLatch startLatch = new CountDownLatch(1); Thread[] threads = new Thread[THREAD_COUNT]; for (int i = 0; i < THREAD_COUNT; ++i) { threads[i] = new Thread() { public void run() { try { startLatch.await(); for (int i = 0; i < 1000; ++i) { Connection conn = dataSource.getConnection(); Thread.sleep(1); conn.close(); } } catch (Exception e) { } finally { endLatch.countDown(); } } }; threads[i].start(); } startLatch.countDown(); endLatch.await(); // System.out.println(dataSource.getNumIdle()); System.out.println(MockDriver.instance.getConnections().size()); System.out.println(MockDriver.instance.getConnectionCloseCount()); }