java.util.concurrent.CountDownLatch Java Examples
The following examples show how to use
java.util.concurrent.CountDownLatch.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultMQPushConsumerTest.java From rocketmq-4.3.0 with Apache License 2.0 | 6 votes |
@Test public void testPullMessage_SuccessWithOrderlyService() throws Exception { final CountDownLatch countDownLatch = new CountDownLatch(1); final MessageExt[] messageExts = new MessageExt[1]; MessageListenerOrderly listenerOrderly = new MessageListenerOrderly() { @Override public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) { messageExts[0] = msgs.get(0); countDownLatch.countDown(); return null; } }; pushConsumer.registerMessageListener(listenerOrderly); pushConsumer.getDefaultMQPushConsumerImpl().setConsumeMessageService(new ConsumeMessageOrderlyService(pushConsumer.getDefaultMQPushConsumerImpl(), listenerOrderly)); pushConsumer.getDefaultMQPushConsumerImpl().setConsumeOrderly(true); pushConsumer.getDefaultMQPushConsumerImpl().doRebalance(); PullMessageService pullMessageService = mQClientFactory.getPullMessageService(); pullMessageService.executePullRequestLater(createPullRequest(), 100); countDownLatch.await(10, TimeUnit.SECONDS); assertThat(messageExts[0].getTopic()).isEqualTo(topic); assertThat(messageExts[0].getBody()).isEqualTo(new byte[] {'a'}); }
Example #2
Source File: TestFileWatcher.java From arcusplatform with Apache License 2.0 | 6 votes |
@Test public void testWatchFileRelativePath() throws Exception { URI uri = new URI(tempFile.getName()); Resource resource = factory.create(uri); verifyResource(resource); final CountDownLatch latch = new CountDownLatch(1); resource.addWatch(new ResourceListener() { @Override public void onChange() { latch.countDown(); } }); // Give the file watcher a second to get started. Thread.sleep(1000); writeLineToFile(TEST_DATA); // It can take a few seconds for the event to get fired. boolean changeDetected = latch.await(20, TimeUnit.SECONDS); assertTrue(changeDetected); try(BufferedReader reader = new BufferedReader(new InputStreamReader( resource.open()))) { assertEquals(TEST_DATA, reader.readLine()); } }
Example #3
Source File: ZKClientImpl.java From bistoury with GNU General Public License v3.0 | 6 votes |
private void waitUntilZkStart() { final CountDownLatch latch = new CountDownLatch(1); addConnectionChangeListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState == ConnectionState.CONNECTED) { latch.countDown(); } } }); client.start(); try { latch.await(); } catch (InterruptedException e) { logger.error("start zk latch.await() error", e); Thread.currentThread().interrupt(); } }
Example #4
Source File: HashedWheelTimerTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void testNewTimeoutShouldStopThrowingRejectedExecutionExceptionWhenExistingTimeoutIsCancelled() throws InterruptedException { final int tickDurationMs = 100; final HashedWheelTimer timer = new HashedWheelTimer(Executors.defaultThreadFactory(), tickDurationMs, TimeUnit.MILLISECONDS, 32, true, 2); timer.newTimeout(createNoOpTimerTask(), 5, TimeUnit.SECONDS); Timeout timeoutToCancel = timer.newTimeout(createNoOpTimerTask(), 5, TimeUnit.SECONDS); assertTrue(timeoutToCancel.cancel()); Thread.sleep(tickDurationMs * 5); final CountDownLatch secondLatch = new CountDownLatch(1); timer.newTimeout(createCountDownLatchTimerTask(secondLatch), 90, TimeUnit.MILLISECONDS); secondLatch.await(); timer.stop(); }
Example #5
Source File: DefaultMQPushConsumerTest.java From rocketmq-4.3.0 with Apache License 2.0 | 6 votes |
@Test public void testPullMessage_Success() throws InterruptedException, RemotingException, MQBrokerException { final CountDownLatch countDownLatch = new CountDownLatch(1); final MessageExt[] messageExts = new MessageExt[1]; pushConsumer.getDefaultMQPushConsumerImpl().setConsumeMessageService(new ConsumeMessageConcurrentlyService(pushConsumer.getDefaultMQPushConsumerImpl(), new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { messageExts[0] = msgs.get(0); countDownLatch.countDown(); return null; } })); PullMessageService pullMessageService = mQClientFactory.getPullMessageService(); pullMessageService.executePullRequestImmediately(createPullRequest()); countDownLatch.await(); assertThat(messageExts[0].getTopic()).isEqualTo(topic); assertThat(messageExts[0].getBody()).isEqualTo(new byte[] {'a'}); }
Example #6
Source File: GattConnectDisconnectTests.java From bitgatt with Mozilla Public License 2.0 | 6 votes |
@Test public void testServerConnect() throws Exception { // started FitbitGatt.getInstance().startGattServer(mockContext); Assert.assertTrue(FitbitGatt.getInstance().isInitialized()); FitbitBluetoothDevice device = new FitbitBluetoothDevice(MOCK_ADDRESS, "fooDevice"); GattServerConnection connection = new GattServerConnection(null, Looper.getMainLooper()); connection.setMockMode(true); connection.setState(GattState.DISCONNECTED); CountDownLatch cdl = new CountDownLatch(1); GattServerConnectMockTransaction connectTransaction = new GattServerConnectMockTransaction(connection, GattState.CONNECTED, device, false); connection.runTx(connectTransaction, result -> { Timber.w("Transaction result %s", result); assertTrue(result.resultStatus.equals(TransactionResult.TransactionResultStatus.SUCCESS) && connection.getGattState().equals(GattState.CONNECTED)); cdl.countDown(); }); cdl.await(1, TimeUnit.SECONDS); }
Example #7
Source File: FileLoadOperation.java From TelePlus-Android with GNU General Public License v2.0 | 6 votes |
protected File getCurrentFile() { final CountDownLatch countDownLatch = new CountDownLatch(1); final File result[] = new File[1]; Utilities.stageQueue.postRunnable(new Runnable() { @Override public void run() { if (state == stateFinished) { result[0] = cacheFileFinal; } else { result[0] = cacheFileTemp; } countDownLatch.countDown(); } }); try { countDownLatch.await(); } catch (Exception e) { FileLog.e(e); } return result[0]; }
Example #8
Source File: SingleThreadEventLoopTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("deprecation") public void shutdownAfterStart() throws Exception { final CountDownLatch latch = new CountDownLatch(1); loopA.execute(new Runnable() { @Override public void run() { latch.countDown(); } }); // Wait for the event loop thread to start. latch.await(); // Request the event loop thread to stop. loopA.shutdown(); assertRejection(loopA); assertTrue(loopA.isShutdown()); // Wait until the event loop is terminated. while (!loopA.isTerminated()) { loopA.awaitTermination(1, TimeUnit.DAYS); } }
Example #9
Source File: DefaultChannelPipelineTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test(timeout = 5000) public void testChannelInitializerException() throws Exception { final IllegalStateException exception = new IllegalStateException(); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); final CountDownLatch latch = new CountDownLatch(1); EmbeddedChannel channel = new EmbeddedChannel(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { throw exception; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { super.exceptionCaught(ctx, cause); error.set(cause); latch.countDown(); } }); latch.await(); assertFalse(channel.isActive()); assertSame(exception, error.get()); }
Example #10
Source File: TransactionQueueControllerTest.java From bitgatt with Mozilla Public License 2.0 | 6 votes |
@Test public void controllerShouldHandleInterupts() { CountDownLatch cdl = new CountDownLatch(1); assertTrue(sut.isQueueThreadStopped()); sut.queueTransaction(() -> { cdl.countDown(); Thread.currentThread().interrupt(); }); try { cdl.await(100, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { fail("Latch interrupted"); } assertEquals(0, cdl.getCount()); assertFalse(sut.isQueueThreadStopped()); }
Example #11
Source File: DatagramUnicastTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@SuppressWarnings("deprecation") private Channel setupServerChannel(Bootstrap sb, final byte[] bytes, final CountDownLatch latch) throws Throwable { sb.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() { @Override public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { ByteBuf buf = msg.content(); assertEquals(bytes.length, buf.readableBytes()); for (byte b : bytes) { assertEquals(b, buf.readByte()); } latch.countDown(); } }); } }); return sb.bind(newSocketAddress()).sync().channel(); }
Example #12
Source File: StaticServerPollerTest.java From mantis with Apache License 2.0 | 6 votes |
@Test public void pollingIsScheduled() throws Exception { StaticServerPoller poller = new StaticServerPoller(servers, pollingInterval); final AtomicInteger count = new AtomicInteger(); final CountDownLatch done = new CountDownLatch(5); long start = System.currentTimeMillis(); poller.servers() .doOnNext(new Action1<Set<ServerInfo>>() { @Override public void call(Set<ServerInfo> data) { assertEquals("We should always see the same set of servers", servers, data); count.incrementAndGet(); done.countDown(); } }) .subscribe(); done.await(); long elapsed = (System.currentTimeMillis() - start) / 1000; System.out.println(elapsed); assertTrue("The poller should have polled 5 times and the elaspsed time should be greater than 3", count.get() == 5 && elapsed <= 6); }
Example #13
Source File: EmbeddedChannelTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void testHandleOutboundMessage() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); EmbeddedChannel channel = new EmbeddedChannel() { @Override protected void handleOutboundMessage(Object msg) { latch.countDown(); } }; channel.writeOneOutbound("Hello, Netty!"); if (latch.await(50L, TimeUnit.MILLISECONDS)) { fail("Somebody called unexpectedly #flush()"); } channel.flushOutbound(); if (!latch.await(1L, TimeUnit.SECONDS)) { fail("Nobody called #handleOutboundMessage() in time."); } }
Example #14
Source File: AbstractChannelManager.java From joyrpc with Apache License 2.0 | 6 votes |
@Override public boolean close() { CountDownLatch latch = new CountDownLatch(1); final Throwable[] err = new Throwable[1]; final boolean[] res = new boolean[]{false}; try { close(r -> { if (r.getThrowable() != null) { err[0] = r.getThrowable(); } else if (!r.isSuccess()) { res[0] = false; } }); latch.await(); } catch (InterruptedException e) { } if (err[0] != null) { throw new TransportException(err[0]); } return res[0]; }
Example #15
Source File: PluginTaskExecutorTest.java From hivemq-community-edition with Apache License 2.0 | 6 votes |
@Test(timeout = 5000) public void test_multiple_out_tasks_for_different_clients_from_different_producers_are_executed() throws Exception { final int tries = 250; final int threads = 4; final CountDownLatch latch = new CountDownLatch(tries * threads); final ExecutorService executorService = Executors.newFixedThreadPool(threads); for (int j = 0; j < threads; j++) { final int finalJ = j; executorService.execute(() -> { for (int i = finalJ * tries; i < (tries * finalJ) + tries; i++) { addOutTask(pluginTaskExecutor, latch, "" + (i % 100), false, i, executionOrder, 0, classloader); } }); } assertTrue(latch.await(30, TimeUnit.SECONDS)); }
Example #16
Source File: TestTheaterSpec.java From swim with Apache License 2.0 | 6 votes |
@Test public void invokeTaskLifecycleCallbacks() { final TestTheater theater = new TestTheater(); final CountDownLatch taskWillCue = new CountDownLatch(1); try { theater.start(); final TaskRef task = theater.task(new AbstractTask() { @Override public void runTask() { // nop } @Override public void taskWillCue() { assertEquals(taskWillCue.getCount(), 1); taskWillCue.countDown(); } }); task.cue(); theater.await(taskWillCue); } finally { theater.stop(); } }
Example #17
Source File: CompletionHandlerRelease.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
@Test public void testConnect() throws Exception { try (Server server = new Server()) { try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open(GROUP)) { CountDownLatch latch = new CountDownLatch(1); Handler<Void,Object> handler = new Handler<Void,Object>("connect", latch); ReferenceQueue queue = new ReferenceQueue<WeakReference>(); WeakReference<Object> ref = new WeakReference<Object>(handler, queue); ch.connect(server.address(), null, handler); try { latch.await(); } catch (InterruptedException ignore) { } handler = null; waitForRefToClear(ref, queue); server.accept().get().close(); } } }
Example #18
Source File: CancelDelaySend.java From DDMQ with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { CarreraProducer producer; List<String> ips = new ArrayList(); ips.add("127.0.0.1:9613"); CarreraConfig carreraConfig = new CarreraConfig(); carreraConfig.setCarreraProxyList(ips); carreraConfig.setCarreraProxyTimeout(200); carreraConfig.setCarreraClientRetry(3); carreraConfig.setCarreraClientTimeout(300); carreraConfig.setCarreraPoolSize(10); producer = new CarreraProducer(carreraConfig); ExecutorService executorService = Executors.newFixedThreadPool(100); producer.start(); CountDownLatch cdl = new CountDownLatch(100); for (int i = 0; i < 100; i++) { executorService.execute(() -> { sendMsg(producer); cdl.countDown(); }); } cdl.await(); producer.shutdown(); }
Example #19
Source File: XodusLocalPersistence.java From hivemq-community-edition with Apache License 2.0 | 5 votes |
@Override public void start() { final String name = getName(); final String version = getVersion(); final int bucketCount = getBucketCount(); final StoreConfig storeConfig = getStoreConfig(); final Logger logger = getLogger(); try { final EnvironmentConfig environmentConfig = environmentUtil.createEnvironmentConfig(name); final File persistenceFolder = localPersistenceFileUtil.getVersionedLocalPersistenceFolder(name, version); final CountDownLatch counter = new CountDownLatch(bucketCount); for (int i = 0; i < bucketCount; i++) { final int finalI = i; persistenceStartup.submitEnvironmentCreate(() -> { final File persistenceFile = new File(persistenceFolder, name + "_" + finalI); final Environment environment = Environments.newContextualInstance(persistenceFile, environmentConfig); final Store store = environment.computeInTransaction(txn -> environment.openStore(name, storeConfig, txn)); buckets[finalI] = new Bucket(environment, store); counter.countDown(); }); } counter.await(); } catch (final ExodusException | InterruptedException e) { logger.error("An error occurred while opening the {} persistence. Is another HiveMQ instance running?", name); logger.debug("Original Exception:", e); throw new UnrecoverableException(); } init(); }
Example #20
Source File: Http2CodecClientMain.java From joyrpc with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { URL url = URL.valueOf("http2://127.0.0.1:22000"); Client client = new DefaultEndpointFactory().createClient(url); client.setCodec(new MockHttp2Codec()); ChannelHandlerChain channelHandlerChain = new ChannelHandlerChain() .addLast(new MockCoverChannelHandler()) .addLast(new MockResponseChannelHandler()); client.setChannelHandlerChain(channelHandlerChain); client.open(); Message responseMsg = client.sync(createMockMessage("first sync mock", MsgType.BizReq), 500000); logger.info("receive sync response: " + responseMsg); client.oneway(createMockMessage("first oneway mock", MsgType.BizReq)); client.oneway(createMockMessage("second oneway mock", MsgType.BizReq)); CountDownLatch latch = new CountDownLatch(1); client.async( createMockMessage("first async mock", MsgType.BizReq), (msg, err) -> { if (err != null) { logger.error("get resp error:{}" + err.getMessage(), err); } else { logger.info("get resp" + msg); } latch.countDown(); }, 1000); latch.await(1500, TimeUnit.MILLISECONDS); client.close(); }
Example #21
Source File: SpoolingRawBatchBuffer.java From Bats with Apache License 2.0 | 5 votes |
public RawFragmentBatchWrapper(RawFragmentBatch batch, boolean available) { Preconditions.checkNotNull(batch); this.batch = batch; this.available = available; this.latch = new CountDownLatch(available ? 0 : 1); if (available) { batch.sendOk(); } }
Example #22
Source File: KafkaConnectRunnerService.java From camel-kafka-connector with Apache License 2.0 | 5 votes |
public void start() { CountDownLatch latch = new CountDownLatch(1); service.submit(() -> kafkaConnectRunner.run(latch)); try { if (!latch.await(30, TimeUnit.SECONDS)) { LOG.warn("The Kafka Connect Runner timed out while initializing"); throw new RuntimeException("The Kafka Connect Runner timed out while initializing"); } } catch (InterruptedException e) { LOG.error("The test was interrupted while executing"); } }
Example #23
Source File: TableStoreDataFetcher.java From tablestore-examples with Apache License 2.0 | 5 votes |
public GridDataSet fetch() throws Exception { long totalFetchDataSize = calcDataSize(variables.size()); if (totalFetchDataSize == 0) { throw new RuntimeException("no data to fetch"); } if (totalFetchDataSize > dataSizeLimitForFetch) { throw new RuntimeException("exceed the max data limit for fetch"); } GridDataSet dataSet = new GridDataSet(meta); CountDownLatch latch = new CountDownLatch(variables.size() * tRange.getSize() * zRange.getSize()); Queue<Exception> exceptions = new ConcurrentLinkedQueue<Exception>(); AtomicInteger counter = new AtomicInteger(); int taskCount = 0; for (String variable : variables) { int dataSize = (int) calcDataSize(1); byte[] data = new byte[dataSize]; ByteBuffer buffer = ByteBuffer.wrap(data).asReadOnlyBuffer(); dataSet.addVariable(variable, new Grid4D(buffer, meta.getDataType(), getOrigin(), getShape())); int curPos = 0; for (int t = tRange.getStart(); t < tRange.getEnd(); t++) { for (int z = zRange.getStart(); z < zRange.getEnd(); z++) { addTask(counter, data, curPos, variable, t, z, latch, exceptions); curPos += xRange.getSize() * yRange.getSize() * meta.getDataType().getSize(); taskCount++; } } } latch.await(); if (!exceptions.isEmpty()) { throw exceptions.peek(); } if (counter.get() != taskCount) { throw new RuntimeException("not all task success"); } return dataSet; }
Example #24
Source File: BenchmarkClient.java From dubbo-2.6.5 with Apache License 2.0 | 5 votes |
@Override public ClientRunnable getClientRunnable(String targetIP, int targetPort, int clientNums, int rpcTimeout, CyclicBarrier barrier, CountDownLatch latch, long endTime, long startTime) { return new SimpleProcessorBenchmarkClientRunnable(targetIP, targetPort, clientNums, rpcTimeout, barrier, latch, startTime, endTime); }
Example #25
Source File: MailboxImplTest.java From flink with Apache License 2.0 | 5 votes |
private void testUnblocksInternal( RunnableWithException testMethod, Consumer<Mailbox> unblockMethod) throws InterruptedException { final Thread[] blockedThreads = new Thread[8]; final Exception[] exceptions = new Exception[blockedThreads.length]; CountDownLatch countDownLatch = new CountDownLatch(blockedThreads.length); for (int i = 0; i < blockedThreads.length; ++i) { final int id = i; Thread blocked = new Thread(() -> { try { countDownLatch.countDown(); while (true) { testMethod.run(); } } catch (Exception ex) { exceptions[id] = ex; } }); blockedThreads[i] = blocked; blocked.start(); } countDownLatch.await(); unblockMethod.accept(mailbox); for (Thread blockedThread : blockedThreads) { blockedThread.join(); } for (Exception exception : exceptions) { Assert.assertEquals(MailboxStateException.class, exception.getClass()); } }
Example #26
Source File: PluginTaskExecutorTest.java From hivemq-community-edition with Apache License 2.0 | 5 votes |
private static void addExceptionPostTask(final PluginTaskExecutor pluginTaskExecutor, @NotNull final CountDownLatch latch, final boolean async, @NotNull final List<Integer> executionOrder, @NotNull final IsolatedPluginClassloader classloader) { pluginTaskExecutor.handlePluginTaskExecution( new PluginTaskExecution<>(new TestPluginInOutExceptionContext("client"), () -> new TestPluginTaskInput(), () -> async ? new TestPluginTaskOutputAsync() : new TestPluginTaskOutput(), new TestPluginInOutTask(latch, 1, executionOrder, 0, classloader))); }
Example #27
Source File: StreamingConsumerChannel.java From kylin-on-parquet-v2 with Apache License 2.0 | 5 votes |
public StreamingConsumerChannel(String cubeName, IStreamingConnector connector, StreamingSegmentManager cubeSegmentManager, IStopConsumptionCondition stopCondition) { this.connector = connector; this.cubeName = cubeName; this.cubeSegmentManager = cubeSegmentManager; this.stopCondition = stopCondition; this.stopLatch = new CountDownLatch(1); this.eventConsumeMeters = Maps.newHashMap(); this.minAcceptEventTime = 0; }
Example #28
Source File: MockClockSpec.java From swim with Apache License 2.0 | 5 votes |
@Test public void cancelFirstScheduledAndSoonerOfTwoTimersForSameTickOfDifferentRevolutions() { final MockClock clock = new MockClock(100, 512); final CountDownLatch cancel1 = new CountDownLatch(1); final CountDownLatch fire2 = new CountDownLatch(1); try { clock.start(); final TimerRef timer1 = clock.setTimer(100L, new AbstractTimer() { @Override public void runTimer() { fail(); } @Override public void timerDidCancel() { assertEquals(cancel1.getCount(), 1); cancel1.countDown(); } }); clock.setTimer(513L * 100L, new AbstractTimer() { @Override public void runTimer() { assertEquals(clock.tick(), 513L); assertEquals(fire2.getCount(), 1); fire2.countDown(); } }); timer1.cancel(); clock.tick(1); clock.await(cancel1); clock.tick(512); clock.await(fire2); } finally { clock.stop(); } }
Example #29
Source File: ClientFuseTest.java From DeFiBus with Apache License 2.0 | 5 votes |
@Test public void testProcessResponseFuse() throws Exception { when(mqClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(createTopicRoute()); CountDownLatch countDownLatch = new CountDownLatch(1); Field fieldSelector = DeFiBusProducerImpl.class.getDeclaredField("messageQueueSelector"); fieldSelector.setAccessible(true); Field fieldProducer = DeFiBusProducer.class.getDeclaredField("deFiBusProducerImpl"); fieldProducer.setAccessible(true); MessageQueueHealthManager messageQueueHealthManager = ((HealthyMessageQueueSelector) fieldSelector.get(fieldProducer.get(deFiBusProducer))).getMessageQueueHealthManager(); Assert.assertEquals(0, messageQueueHealthManager.faultMap.size()); deFiBusProducer.publish(msg, new SendCallback() { @Override public void onSuccess(SendResult sendResult) { } @Override public void onException(Throwable e) { Assert.fail(e.getMessage()); countDownLatch.countDown(); } }); countDownLatch.await(3000L, TimeUnit.MILLISECONDS); Assert.assertEquals(3, messageQueueHealthManager.faultMap.size()); }
Example #30
Source File: ClientUtil.java From anomaly-detection with Apache License 2.0 | 5 votes |
/** * Send a nonblocking request with a timeout and return response. Blocking is not allowed in a * transport call context. See BaseFuture.blockingAllowed * @param request request like index/search/get * @param LOG log * @param consumer functional interface to operate as a client request like client::get * @param <Request> ActionRequest * @param <Response> ActionResponse * @return the response * @throws ElasticsearchTimeoutException when we cannot get response within time. * @throws IllegalStateException when the waiting thread is interrupted */ public <Request extends ActionRequest, Response extends ActionResponse> Optional<Response> timedRequest( Request request, Logger LOG, BiConsumer<Request, ActionListener<Response>> consumer ) { try { AtomicReference<Response> respReference = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); consumer .accept( request, new LatchedActionListener<Response>( ActionListener .wrap( response -> { respReference.set(response); }, exception -> { LOG.error("Cannot get response for request {}, error: {}", request, exception); } ), latch ) ); if (!latch.await(requestTimeout.getSeconds(), TimeUnit.SECONDS)) { throw new ElasticsearchTimeoutException("Cannot get response within time limit: " + request.toString()); } return Optional.ofNullable(respReference.get()); } catch (InterruptedException e1) { LOG.error(CommonErrorMessages.WAIT_ERR_MSG); throw new IllegalStateException(e1); } }