List of usage examples for java.util.concurrent CountDownLatch getCount
public long getCount()
From source file:org.apache.awf.web.SystemTest.java
@Test public void multipleAsynchronousHttpClientTest() throws InterruptedException { for (int i = 0; i < 100; i++) { final CountDownLatch latch = new CountDownLatch(1); final String url = "http://localhost:" + PORT + "/"; final AsynchronousHttpClient http = new AsynchronousHttpClient(); final String[] result = { "BODY_PLACEHOLDER", "STATUSCODE_PLACEHOLDER" }; final AsyncResult<org.apache.awf.web.http.client.Response> cb = new AsyncResult<org.apache.awf.web.http.client.Response>() { public void onSuccess(org.apache.awf.web.http.client.Response response) { result[0] = response.getBody(); result[1] = response.getStatusLine(); latch.countDown();/*w w w . j a v a 2s. co m*/ } public void onFailure(Throwable ignore) { } }; // make sure that the http.fetch(..) is invoked from the ioloop // thread IOLoop.INSTANCE.addCallback(new AsyncCallback() { public void onCallback() { http.get(url, cb); } }); latch.await(30, TimeUnit.SECONDS); assertEquals(0, latch.getCount()); assertEquals("hello test", result[0]); assertEquals("HTTP/1.1 200 OK", result[1]); } }
From source file:org.springframework.kafka.listener.KafkaMessageListenerContainerTests.java
@Test public void testDefinedPartitions() throws Exception { this.logger.info("Start defined parts"); Map<String, Object> props = KafkaTestUtils.consumerProps("test3", "false", embeddedKafka); TopicPartitionInitialOffset topic1Partition0 = new TopicPartitionInitialOffset(topic13, 0, 0L); CountDownLatch initialConsumersLatch = new CountDownLatch(2); DefaultKafkaConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<Integer, String>(props) { @Override/*w ww . j a v a2s . co m*/ public Consumer<Integer, String> createConsumer() { return new KafkaConsumer<Integer, String>(props) { @Override public ConsumerRecords<Integer, String> poll(long timeout) { try { return super.poll(timeout); } finally { initialConsumersLatch.countDown(); } } }; } }; ContainerProperties container1Props = new ContainerProperties(topic1Partition0); CountDownLatch latch1 = new CountDownLatch(2); container1Props.setMessageListener((MessageListener<Integer, String>) message -> { logger.info("defined part: " + message); latch1.countDown(); }); KafkaMessageListenerContainer<Integer, String> container1 = new KafkaMessageListenerContainer<>(cf, container1Props); container1.setBeanName("b1"); container1.start(); CountDownLatch stopLatch1 = new CountDownLatch(1); willAnswer(invocation -> { try { return invocation.callRealMethod(); } finally { stopLatch1.countDown(); } }).given(spyOnConsumer(container1)).commitSync(any()); TopicPartitionInitialOffset topic1Partition1 = new TopicPartitionInitialOffset(topic13, 1, 0L); ContainerProperties container2Props = new ContainerProperties(topic1Partition1); CountDownLatch latch2 = new CountDownLatch(2); container2Props.setMessageListener((MessageListener<Integer, String>) message -> { logger.info("defined part: " + message); latch2.countDown(); }); KafkaMessageListenerContainer<Integer, String> container2 = new KafkaMessageListenerContainer<>(cf, container2Props); container2.setBeanName("b2"); container2.start(); CountDownLatch stopLatch2 = new CountDownLatch(1); willAnswer(invocation -> { try { return invocation.callRealMethod(); } finally { stopLatch2.countDown(); } }).given(spyOnConsumer(container2)).commitSync(any()); assertThat(initialConsumersLatch.await(20, TimeUnit.SECONDS)).isTrue(); Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka); ProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(senderProps); KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf); template.setDefaultTopic(topic13); template.sendDefault(0, 0, "foo"); template.sendDefault(1, 2, "bar"); template.sendDefault(0, 0, "baz"); template.sendDefault(1, 2, "qux"); template.flush(); assertThat(latch1.await(60, TimeUnit.SECONDS)).isTrue(); assertThat(latch2.await(60, TimeUnit.SECONDS)).isTrue(); assertThat(stopLatch1.await(60, TimeUnit.SECONDS)).isTrue(); container1.stop(); assertThat(stopLatch2.await(60, TimeUnit.SECONDS)).isTrue(); container2.stop(); cf = new DefaultKafkaConsumerFactory<>(props); // reset earliest ContainerProperties container3Props = new ContainerProperties(topic1Partition0, topic1Partition1); CountDownLatch latch3 = new CountDownLatch(4); container3Props.setMessageListener((MessageListener<Integer, String>) message -> { logger.info("defined part e: " + message); latch3.countDown(); }); KafkaMessageListenerContainer<Integer, String> resettingContainer = new KafkaMessageListenerContainer<>(cf, container3Props); resettingContainer.setBeanName("b3"); resettingContainer.start(); CountDownLatch stopLatch3 = new CountDownLatch(1); willAnswer(invocation -> { try { return invocation.callRealMethod(); } finally { stopLatch3.countDown(); } }).given(spyOnConsumer(resettingContainer)).commitSync(any()); assertThat(latch3.await(60, TimeUnit.SECONDS)).isTrue(); assertThat(stopLatch3.await(60, TimeUnit.SECONDS)).isTrue(); resettingContainer.stop(); assertThat(latch3.getCount()).isEqualTo(0L); cf = new DefaultKafkaConsumerFactory<>(props); // reset beginning for part 0, minus one for part 1 topic1Partition0 = new TopicPartitionInitialOffset(topic13, 0, -1000L); topic1Partition1 = new TopicPartitionInitialOffset(topic13, 1, -1L); ContainerProperties container4Props = new ContainerProperties(topic1Partition0, topic1Partition1); CountDownLatch latch4 = new CountDownLatch(3); AtomicReference<String> receivedMessage = new AtomicReference<>(); container4Props.setMessageListener((MessageListener<Integer, String>) message -> { logger.info("defined part 0, -1: " + message); receivedMessage.set(message.value()); latch4.countDown(); }); resettingContainer = new KafkaMessageListenerContainer<>(cf, container4Props); resettingContainer.setBeanName("b4"); resettingContainer.start(); CountDownLatch stopLatch4 = new CountDownLatch(1); willAnswer(invocation -> { try { return invocation.callRealMethod(); } finally { stopLatch4.countDown(); } }).given(spyOnConsumer(resettingContainer)).commitSync(any()); assertThat(latch4.await(60, TimeUnit.SECONDS)).isTrue(); assertThat(stopLatch4.await(60, TimeUnit.SECONDS)).isTrue(); resettingContainer.stop(); assertThat(receivedMessage.get()).isIn("baz", "qux"); assertThat(latch4.getCount()).isEqualTo(0L); // reset plus one template.sendDefault(0, 0, "FOO"); template.sendDefault(1, 2, "BAR"); template.flush(); topic1Partition0 = new TopicPartitionInitialOffset(topic13, 0, 1L); topic1Partition1 = new TopicPartitionInitialOffset(topic13, 1, 1L); ContainerProperties container5Props = new ContainerProperties(topic1Partition0, topic1Partition1); final CountDownLatch latch5 = new CountDownLatch(4); final List<String> messages = new ArrayList<>(); container5Props.setMessageListener((MessageListener<Integer, String>) message -> { logger.info("defined part 1: " + message); messages.add(message.value()); latch5.countDown(); }); resettingContainer = new KafkaMessageListenerContainer<>(cf, container5Props); resettingContainer.setBeanName("b5"); resettingContainer.start(); CountDownLatch stopLatch5 = new CountDownLatch(1); willAnswer(invocation -> { try { return invocation.callRealMethod(); } finally { stopLatch5.countDown(); } }).given(spyOnConsumer(resettingContainer)).commitSync(any()); assertThat(latch5.await(60, TimeUnit.SECONDS)).isTrue(); assertThat(stopLatch5.await(60, TimeUnit.SECONDS)).isTrue(); resettingContainer.stop(); assertThat(messages).contains("baz", "qux", "FOO", "BAR"); this.logger.info("+++++++++++++++++++++ Start relative reset"); template.sendDefault(0, 0, "BAZ"); template.sendDefault(1, 2, "QUX"); template.sendDefault(0, 0, "FIZ"); template.sendDefault(1, 2, "BUZ"); template.flush(); topic1Partition0 = new TopicPartitionInitialOffset(topic13, 0, 1L, true); topic1Partition1 = new TopicPartitionInitialOffset(topic13, 1, -1L, true); ContainerProperties container6Props = new ContainerProperties(topic1Partition0, topic1Partition1); final CountDownLatch latch6 = new CountDownLatch(4); final List<String> messages6 = new ArrayList<>(); container6Props.setMessageListener((MessageListener<Integer, String>) message -> { logger.info("defined part relative: " + message); messages6.add(message.value()); latch6.countDown(); }); resettingContainer = new KafkaMessageListenerContainer<>(cf, container6Props); resettingContainer.setBeanName("b6"); resettingContainer.start(); CountDownLatch stopLatch6 = new CountDownLatch(1); willAnswer(invocation -> { try { return invocation.callRealMethod(); } finally { stopLatch6.countDown(); } }).given(spyOnConsumer(resettingContainer)).commitSync(any()); assertThat(latch6.await(60, TimeUnit.SECONDS)).isTrue(); assertThat(stopLatch6.await(60, TimeUnit.SECONDS)).isTrue(); resettingContainer.stop(); assertThat(messages6).hasSize(4); assertThat(messages6).contains("FIZ", "BAR", "QUX", "BUZ"); this.logger.info("Stop auto parts"); }
From source file:org.kurento.test.functional.recorder.BaseRecorder.java
protected void checkRecordingFile(String recordingFile, String browserName, Color[] expectedColors, long playTime, String expectedVideoCodec, String expectedAudioCodec) throws InterruptedException { // Checking continuity of the audio Timer gettingStats = new Timer(); final CountDownLatch errorContinuityAudiolatch = new CountDownLatch(1); waitForFileExists(recordingFile);/*from w w w. jav a 2 s .c o m*/ MediaPipeline mp = kurentoClient.createMediaPipeline(); PlayerEndpoint playerEp = new PlayerEndpoint.Builder(mp, recordingFile).build(); WebRtcEndpoint webRtcEp = new WebRtcEndpoint.Builder(mp).build(); playerEp.connect(webRtcEp); // Playing the recording WebRtcTestPage checkPage = getPage(browserName); checkPage.setThresholdTime(checkPage.getThresholdTime() * 2); checkPage.subscribeEvents("playing"); checkPage.initWebRtc(webRtcEp, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY); final CountDownLatch eosLatch = new CountDownLatch(1); playerEp.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() { @Override public void onEvent(EndOfStreamEvent event) { eosLatch.countDown(); } }); playerEp.play(); // Assertions in recording final String messageAppend = "[played file with media pipeline]"; Assert.assertTrue("Not received media in the recording (timeout waiting playing event) " + messageAppend, checkPage.waitForEvent("playing")); checkPage.activatePeerConnectionInboundStats("webRtcPeer.peerConnection"); gettingStats.schedule(new CheckAudioTimerTask(errorContinuityAudiolatch, checkPage), 100, 200); for (Color color : expectedColors) { Assert.assertTrue("The color of the recorded video should be " + color + " " + messageAppend, checkPage.similarColorAt(color, 50, 50)); } Assert.assertTrue("Not received EOS event in player", eosLatch.await(checkPage.getTimeout(), TimeUnit.SECONDS)); gettingStats.cancel(); double currentTime = checkPage.getCurrentTime(); Assert.assertTrue("Error in play time in the recorded video (expected: " + playTime + " sec, real: " + currentTime + " sec) " + messageAppend, checkPage.compare(playTime, currentTime)); Assert.assertTrue("Check audio. There were more than 2 seconds without receiving packets", errorContinuityAudiolatch.getCount() == 1); AssertMedia.assertCodecs(recordingFile, expectedVideoCodec, expectedAudioCodec); AssertMedia.assertDuration(recordingFile, TimeUnit.SECONDS.toMillis(playTime), TimeUnit.SECONDS.toMillis(checkPage.getThresholdTime())); mp.release(); }
From source file:com.netflix.curator.framework.recipes.queue.TestDistributedQueue.java
@Test public void testFlush() throws Exception { final Timing timing = new Timing(); final CountDownLatch latch = new CountDownLatch(1); DistributedQueue<TestQueueItem> queue = null; final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start();//from ww w . ja v a 2s . c o m try { final AtomicBoolean firstTime = new AtomicBoolean(true); queue = new DistributedQueue<TestQueueItem>(client, null, serializer, "/test", new ThreadFactoryBuilder().build(), MoreExecutors.sameThreadExecutor(), 10, true, null, QueueBuilder.NOT_SET, true, 0) { @Override void internalCreateNode(final String path, final byte[] bytes, final BackgroundCallback callback) throws Exception { if (firstTime.compareAndSet(true, false)) { Executors.newSingleThreadExecutor().submit(new Callable<Object>() { @Override public Object call() throws Exception { latch.await(); timing.sleepABit(); client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).inBackground(callback) .forPath(path, bytes); return null; } }); } else { super.internalCreateNode(path, bytes, callback); } } }; queue.start(); queue.put(new TestQueueItem("1")); Assert.assertFalse(queue.flushPuts(timing.forWaiting().seconds(), TimeUnit.SECONDS)); latch.countDown(); Assert.assertTrue(queue.flushPuts(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } finally { if (latch.getCount() > 0) { latch.countDown(); } IOUtils.closeQuietly(queue); IOUtils.closeQuietly(client); } }
From source file:org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator.java
@Override public Launcher decorate(final Launcher launcher, final Node node) { return new Launcher.DecoratedLauncher(launcher) { @Override//from w w w . j a v a 2 s .co m public Proc launch(ProcStarter starter) throws IOException { if (!waitUntilContainerIsReady()) { throw new IOException("Failed to execute shell script inside container " + "[" + containerName + "] of pod [" + podName + "]." + " Timed out waiting for container to become ready!"); } final CountDownLatch started = new CountDownLatch(1); final CountDownLatch finished = new CountDownLatch(1); final AtomicBoolean alive = new AtomicBoolean(false); PrintStream printStream = launcher.getListener().getLogger(); OutputStream stream = printStream; // Do not send this command to the output when in quiet mode if (starter.quiet()) { stream = new NullOutputStream(); printStream = new PrintStream(stream, false, StandardCharsets.UTF_8.toString()); } // we need to keep the last bytes in the stream to parse the exit code as it is printed there // so we use a buffer ExitCodeOutputStream exitCodeOutputStream = new ExitCodeOutputStream(); // send container output both to the job output and our buffer stream = new TeeOutputStream(exitCodeOutputStream, stream); String msg = "Executing shell script inside container [" + containerName + "] of pod [" + podName + "]"; LOGGER.log(Level.FINEST, msg); printStream.println(msg); watch = client.pods().inNamespace(namespace).withName(podName).inContainer(containerName) .redirectingInput().writingOutput(stream).writingError(stream).withTTY() .usingListener(new ExecListener() { @Override public void onOpen(Response response) { alive.set(true); started.countDown(); } @Override public void onFailure(Throwable t, Response response) { alive.set(false); t.printStackTrace(launcher.getListener().getLogger()); started.countDown(); LOGGER.log(Level.FINEST, "onFailure : {0}", finished); if (finished.getCount() == 0) { LOGGER.log(Level.WARNING, "onFailure called but latch already finished. This may be a bug in the kubernetes-plugin"); } finished.countDown(); } @Override public void onClose(int i, String s) { alive.set(false); started.countDown(); LOGGER.log(Level.FINEST, "onClose : {0}", finished); if (finished.getCount() == 0) { LOGGER.log(Level.WARNING, "onClose called but latch already finished. This indicates a bug in the kubernetes-plugin"); } finished.countDown(); } }).exec(); waitQuietly(started); if (starter.pwd() != null) { // We need to get into the project workspace. // The workspace is not known in advance, so we have to execute a cd command. watch.getInput().write( String.format("cd \"%s\"%s", starter.pwd(), NEWLINE).getBytes(StandardCharsets.UTF_8)); } doExec(watch, printStream, getCommands(starter)); proc = new ContainerExecProc(watch, alive, finished, new Callable<Integer>() { @Override public Integer call() { return exitCodeOutputStream.getExitCode(); } }); return proc; } @Override public void kill(Map<String, String> modelEnvVars) throws IOException, InterruptedException { // String cookie = modelEnvVars.get(COOKIE_VAR); // TODO we need to use the cookie for something getListener().getLogger().println("Killing process."); ContainerExecDecorator.this.close(); } private boolean isContainerReady(Pod pod, String container) { if (pod == null || pod.getStatus() == null || pod.getStatus().getContainerStatuses() == null) { return false; } for (ContainerStatus info : pod.getStatus().getContainerStatuses()) { if (info.getName().equals(container) && info.getReady()) { return true; } } return false; } private boolean waitUntilContainerIsReady() { int i = 0; int j = 10; // wait 60 seconds Pod pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod == null) { launcher.getListener().getLogger().println("Waiting for pod [" + podName + "] to exist."); // wait for Pod to be running. for (; i < j; i++) { LOGGER.log(Level.INFO, "Getting pod ({1}/{2}): {0}", new Object[] { podName, i, j }); pod = client.pods().inNamespace(namespace).withName(podName).get(); if (pod != null) { break; } LOGGER.log(Level.INFO, "Waiting 6 seconds before checking if pod exists ({1}/{2}): {0}", new Object[] { podName, i, j }); try { Thread.sleep(6000); } catch (InterruptedException e) { return false; } } } if (pod == null) { throw new IllegalArgumentException("Container with name:[" + containerName + "] not found in pod:[" + podName + "], pod doesn't exist"); } if (isContainerReady(pod, containerName)) { return true; } launcher.getListener().getLogger().println("Waiting for container container [" + containerName + "] of pod [" + podName + "] to become ready."); final CountDownLatch latch = new CountDownLatch(1); Watcher<Pod> podWatcher = new Watcher<Pod>() { @Override public void eventReceived(Action action, Pod resource) { switch (action) { case MODIFIED: if (isContainerReady(resource, containerName)) { latch.countDown(); } break; default: break; } } @Override public void onClose(KubernetesClientException cause) { } }; try (Watch watch = client.pods().inNamespace(namespace).withName(podName).watch(podWatcher)) { if (latch.await(CONTAINER_READY_TIMEOUT, TimeUnit.MINUTES)) { return true; } } catch (InterruptedException e) { return false; } return false; } }; }
From source file:io.realm.TypeBasedNotificationsTests.java
@Test @RunTestInLooperThread// ww w . j a va2s . c om public void refresh_should_notify_callbacks_mixed() { final CountDownLatch listenerWasCalledOnRealmObject = new CountDownLatch(1); final CountDownLatch listenerWasCalledOnRealmResults = new CountDownLatch(1); final Realm realm = looperThread.realm; // Swallow all REALM_CHANGED events to test the behaviour of an explicit refresh final Handler handler = new HandlerProxy(realm.handlerController) { @Override public boolean onInterceptInMessage(int what) { switch (what) { case HandlerController.REALM_CHANGED: { return true; } } return false; } }; realm.setHandler(handler); Dog dog = realm.where(Dog.class).findFirstAsync(); RealmResults<Dog> dogs = realm.where(Dog.class).findAllAsync(); assertTrue(dog.load()); assertTrue(dogs.load()); dog.addChangeListener(new RealmChangeListener() { @Override public void onChange() { listenerWasCalledOnRealmObject.countDown(); if (listenerWasCalledOnRealmObject.getCount() == 0 && listenerWasCalledOnRealmResults.getCount() == 0) { looperThread.testComplete(); } } }); dogs.addChangeListener(new RealmChangeListener() { @Override public void onChange() { listenerWasCalledOnRealmResults.countDown(); if (listenerWasCalledOnRealmObject.getCount() == 0 && listenerWasCalledOnRealmResults.getCount() == 0) { looperThread.testComplete(); } } }); Thread thread = new Thread() { @Override public void run() { Realm bgRealm = Realm.getInstance(looperThread.realmConfiguration); bgRealm.beginTransaction(); Dog akamaru = bgRealm.createObject(Dog.class); akamaru.setName("Akamaru"); bgRealm.commitTransaction(); bgRealm.close(); } }; thread.start(); try { thread.join(); } catch (InterruptedException e) { fail(e.getMessage()); } realm.refresh(); }
From source file:org.apache.awf.web.SystemTest.java
@Test public void doSimpleAsyncRequestTestWithNing() throws IOException, InterruptedException { int iterations = 100; final CountDownLatch latch = new CountDownLatch(iterations); AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); for (int i = 1; i <= iterations; i++) { asyncHttpClient.prepareGet("http://localhost:" + PORT + "/") .execute(new AsyncCompletionHandler<com.ning.http.client.Response>() { @Override/*from ww w . ja va 2 s . c o m*/ public com.ning.http.client.Response onCompleted(com.ning.http.client.Response response) throws Exception { String body = response.getResponseBody(); assertEquals(expectedPayload, body); { List<String> expectedHeaders = Arrays.asList( new String[] { "Server", "Date", "Content-Length", "Etag", "Connection" }); assertEquals(HttpStatus.SUCCESS_OK.code(), response.getStatusCode()); assertEquals(expectedHeaders.size(), response.getHeaders().size()); for (String header : expectedHeaders) { assertTrue(response.getHeader(header) != null); } assertEquals(expectedPayload.length() + "", response.getHeader("Content-Length")); } latch.countDown(); return response; } @Override public void onThrowable(Throwable t) { assertTrue(false); } }); } latch.await(15 * 1000, TimeUnit.MILLISECONDS); assertEquals(0, latch.getCount()); }
From source file:com.alibaba.otter.node.etl.common.db.DbPerfIntergration.java
@Test public void test_stack() { DbMediaSource dbMediaSource = new DbMediaSource(); dbMediaSource.setId(1L);// w w w .j a v a2 s . c om dbMediaSource.setDriver("com.mysql.jdbc.Driver"); dbMediaSource.setUsername("otter"); dbMediaSource.setPassword("otter"); dbMediaSource.setUrl("jdbc:mysql://127.0.0.1:3306/retl"); dbMediaSource.setEncode("UTF-8"); dbMediaSource.setType(DataMediaType.MYSQL); DbDataMedia dataMedia = new DbDataMedia(); dataMedia.setSource(dbMediaSource); dataMedia.setId(1L); dataMedia.setName("ljhtable1"); dataMedia.setNamespace("otter"); final DbDialect dbDialect = dbDialectFactory.getDbDialect(2L, dataMedia.getSource()); want.object(dbDialect).clazIs(MysqlDialect.class); final TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate(); // ?? int minute = 5; int nextId = 1; final int thread = 10; final int batch = 50; final String sql = "insert into otter.ljhtable1 values(? , ? , ? , ?)"; final CountDownLatch latch = new CountDownLatch(thread); ExecutorService executor = new ThreadPoolExecutor(thread, thread, 60, TimeUnit.SECONDS, new ArrayBlockingQueue(thread * 2), new NamedThreadFactory("load"), new ThreadPoolExecutor.CallerRunsPolicy()); for (int sec = 0; sec < minute * 60; sec++) { // long startTime = System.currentTimeMillis(); for (int i = 0; i < thread; i++) { final int start = nextId + i * batch; executor.submit(new Runnable() { public void run() { try { transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { JdbcTemplate jdbcTemplate = dbDialect.getJdbcTemplate(); return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int idx) throws SQLException { int id = start + idx; StatementCreatorUtils.setParameterValue(ps, 1, Types.INTEGER, null, id); StatementCreatorUtils.setParameterValue(ps, 2, Types.VARCHAR, null, RandomStringUtils.randomAlphabetic(1000)); // RandomStringUtils.randomAlphabetic() long time = new Date().getTime(); StatementCreatorUtils.setParameterValue(ps, 3, Types.TIMESTAMP, new Timestamp(time)); StatementCreatorUtils.setParameterValue(ps, 4, Types.TIMESTAMP, new Timestamp(time)); } public int getBatchSize() { return batch; } }); } }); } finally { latch.countDown(); } } }); } long endTime = System.currentTimeMillis(); try { latch.await(1000 * 60L - (endTime - startTime), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } if (latch.getCount() != 0) { System.out.println("perf is not enough!"); System.exit(-1); } endTime = System.currentTimeMillis(); System.out.println("Time cost : " + (System.currentTimeMillis() - startTime)); try { TimeUnit.MILLISECONDS.sleep(1000L - (endTime - startTime)); } catch (InterruptedException e) { e.printStackTrace(); } nextId = nextId + thread * batch; } executor.shutdown(); }
From source file:org.springframework.integration.ip.tcp.connection.TcpNioConnectionTests.java
@Test public void testAllMessagesDelivered() throws Exception { final int numberOfSockets = 100; TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0); factory.setApplicationEventPublisher(nullPublisher); CompositeExecutor compositeExec = compositeExecutor(); factory.setTaskExecutor(compositeExec); final CountDownLatch latch = new CountDownLatch(numberOfSockets * 4); factory.registerListener(new TcpListener() { @Override// w w w.ja v a 2 s . c o m public boolean onMessage(Message<?> message) { if (!(message instanceof ErrorMessage)) { latch.countDown(); } return false; } }); factory.start(); TestingUtilities.waitListening(factory, null); int port = factory.getPort(); Socket[] sockets = new Socket[numberOfSockets]; for (int i = 0; i < numberOfSockets; i++) { Socket socket = null; int n = 0; while (n++ < 100) { try { socket = SocketFactory.getDefault().createSocket("localhost", port); break; } catch (ConnectException e) { } Thread.sleep(100); } assertTrue("Could not open socket to localhost:" + port, n < 100); sockets[i] = socket; } for (int i = 0; i < numberOfSockets; i++) { sockets[i].getOutputStream().write("foo1 and...".getBytes()); sockets[i].getOutputStream().flush(); } Thread.sleep(100); for (int i = 0; i < numberOfSockets; i++) { sockets[i].getOutputStream().write(("...foo2\r\nbar1 and...").getBytes()); sockets[i].getOutputStream().flush(); } for (int i = 0; i < numberOfSockets; i++) { sockets[i].getOutputStream().write(("...bar2\r\n").getBytes()); sockets[i].getOutputStream().flush(); } for (int i = 0; i < numberOfSockets; i++) { sockets[i].getOutputStream().write("foo3 and...".getBytes()); sockets[i].getOutputStream().flush(); } Thread.sleep(100); for (int i = 0; i < numberOfSockets; i++) { sockets[i].getOutputStream().write(("...foo4\r\nbar3 and...").getBytes()); sockets[i].getOutputStream().flush(); } for (int i = 0; i < numberOfSockets; i++) { sockets[i].getOutputStream().write(("...bar4\r\n").getBytes()); sockets[i].close(); } assertTrue("latch is still " + latch.getCount(), latch.await(60, TimeUnit.SECONDS)); factory.stop(); }