Java Code Examples for java.util.concurrent.CountDownLatch#await()

The following examples show how to use java.util.concurrent.CountDownLatch#await() . These examples are extracted from open source projects. 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 Project: tunnel   File: PrometheusMain.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    ExporterConfig config = new ExporterConfig();
    TunnelExporter exporter = new PrometheusExporter(config);
    TunnelMonitor monitor = exporter.getTunnelMonitor();
    exporter.startup();
    int total = 10;
    CountDownLatch latch = new CountDownLatch(total);
    Thread[] threads = new Thread[total];
    IntStream.range(0, total).forEach(i -> {
        threads[i] = new Thread(() -> {
            monitor.collect(Statics.createStatics("testApp" + i, "testDb" + i, "sn" + i, "table" + i, i, "target" + i, "error" + i));
            latch.countDown();
        });
        threads[i].start();
    });
    try {
        latch.await();
    } catch (Exception e) {
        //
    }

    exporter.destroy();
}
 
Example 2
Source Project: smallrye-graphql   File: LRUCacheTest.java    License: Apache License 2.0 6 votes vote down vote up
private void testWorker(LRUCache<Integer, Integer> lruCache, Function<Integer, Integer> function) throws Exception {
    int numThreads = Runtime.getRuntime().availableProcessors() * 2;
    final CountDownLatch latch = new CountDownLatch(numThreads);
    Thread[] ts = new Thread[numThreads];
    for (int i = 0; i < numThreads; ++i) {
        ts[i] = new Thread(() -> {
            latch.countDown();
            try {
                latch.await();
                for (int j = 0; j < 100000; j++) {
                    lruCache.computeIfAbsent(function.apply(j), k -> {
                        return k;
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        ts[i].start();
    }
    for (int i = 0; i < numThreads; ++i) {
        ts[i].join();
    }
}
 
Example 3
@Test
public void testHandleInboundMessage() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    EmbeddedChannel channel = new EmbeddedChannel() {
        @Override
        protected void handleInboundMessage(Object msg) {
            latch.countDown();
        }
    };

    channel.writeOneInbound("Hello, Netty!");

    if (!latch.await(1L, TimeUnit.SECONDS)) {
        fail("Nobody called #handleInboundMessage() in time.");
    }
}
 
Example 4
Source Project: Project   File: DateFormatExample2.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    ExecutorService executorService = Executors.newCachedThreadPool();
    final Semaphore semaphore = new Semaphore(threadTotal);
    final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
    for (int i = 0; i < clientTotal ; i++) {
        executorService.execute(() -> {
            try {
                semaphore.acquire();
                update();
                semaphore.release();
            } catch (Exception e) {
                log.error("exception", e);
            }
            countDownLatch.countDown();
        });
    }
    countDownLatch.await();
    executorService.shutdown();
}
 
Example 5
@After
public void tearDown() throws Exception {
	try {
		this.client.shutdown();
	}
	catch (Throwable ex) {
		logger.error("Failed to shut client", ex);
	}
	final CountDownLatch latch = new CountDownLatch(1);
	this.activeMQBroker.addShutdownHook(latch::countDown);
	logger.debug("Stopping ActiveMQ broker and will await shutdown");
	this.activeMQBroker.stop();
	if (!latch.await(5, TimeUnit.SECONDS)) {
		logger.debug("ActiveMQ broker did not shut in the expected time.");
	}
}
 
Example 6
Source Project: jkube   File: LazyBuilderTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void getConcurrentShouldInvokeSupplierTwice() throws Exception {
  // Given
  final AtomicInteger count = new AtomicInteger(0);
  final CountDownLatch cdl = new CountDownLatch(1);
  final Supplier<Integer> build = () -> {
    try {
      if (count.incrementAndGet() == 1) {
        cdl.await(100, TimeUnit.MILLISECONDS);
        return 1337; // This value should be ignored, value set by main thread should be preferred in LazyBuilder
      }
    } catch (InterruptedException ignored) {}
    return 1;
  };
  final LazyBuilder<Integer> lazyBuilder = new LazyBuilder<>(build);
  final ExecutorService es = Executors.newSingleThreadExecutor();
  final Future<Integer> concurrentResult = es.submit(lazyBuilder::get);
  // When
  final int result = IntStream.rangeClosed(1, 10).map(t -> lazyBuilder.get()).sum();
  cdl.countDown();
  // Then
  assertThat(count.get(), is(2));
  assertThat(result, is(10));
  assertThat(concurrentResult.get(100, TimeUnit.MILLISECONDS), is(1));
}
 
Example 7
Source Project: Tomcat8-Source-Read   File: CheckOutThreadTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testDBCPThreads10Connections10Validate() throws Exception {
    this.datasource.getPoolProperties().setMaxActive(10);
    this.datasource.getPoolProperties().setTestOnBorrow(true);
    this.threadcount = 10;
    this.transferProperties();
    this.tDatasource.getConnection().close();
    latch = new CountDownLatch(threadcount);
    long start = System.currentTimeMillis();
    for (int i=0; i<threadcount; i++) {
        TestThread t = new TestThread();
        t.setName("tomcat-dbcp-validate-"+i);
        t.d = this.tDatasource;
        t.start();
    }
    latch.await();
    long delta = System.currentTimeMillis() - start;
    System.out.println("[testDBCPThreads10Connections10Validate]Test complete:"+delta+" ms. Iterations:"+(threadcount*this.iterations));
    tearDown();
}
 
Example 8
@Override
public void run() {
    CountDownLatch cl = new CountDownLatch(Resources.Thread_Count);
    for(int i = 0; i< Resources.Thread_Count; i++){
        new Thread(new SingleTask(cl)).start();
    }
    Loading loading = new Loading(filechooser);
    try {
        loading.startloading();
        cl.await();
    }catch (InterruptedException ie){
    //ingore I think this won't happen ever.

    }finally {
        loading.stoploading();
        Toolkit.getDefaultToolkit().beep();
        JOptionPane.showMessageDialog(null, "本次转化完毕,转换后的MP3音频在QMCFLAC目录下", "操作提示",JOptionPane.INFORMATION_MESSAGE);
    }
}
 
Example 9
Source Project: waltz   File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean awaitMetadata(int numReplicas, long currentSessionId, ZooKeeperClient zkClient, ZNode znode) throws Exception {
    CountDownLatch metadataDone = new CountDownLatch(1);
    zkClient.watch(
        znode, n -> {
            PartitionMetadata metadata = n.value;
            if (metadata != null) {
                int count = 0;
                for (ReplicaState replicaState : metadata.replicaStates.values()) {
                    if (currentSessionId == replicaState.sessionId) {
                        count++;
                    }
                }
                if (count == numReplicas) {
                    metadataDone.countDown();
                }
            }
        },
        PartitionMetadataSerializer.INSTANCE,
        true
    );
    return metadataDone.await(10000, TimeUnit.MILLISECONDS);
}
 
Example 10
Source Project: ghidra   File: SwingUpdateManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCallToUpdateWhileAnUpdateIsWorking() throws Exception {

	//
	// Test that an update call from a non-swing thread will still get processed if the
	// manager is actively processing an update on the swing thread.
	//

	CountDownLatch startLatch = new CountDownLatch(1);
	CountDownLatch endLatch = new CountDownLatch(1);
	AtomicBoolean exception = new AtomicBoolean();

	Runnable r = () -> {
		runnableCalled++;

		startLatch.countDown();
		try {
			endLatch.await(10, TimeUnit.SECONDS);
		}
		catch (InterruptedException e) {
			exception.set(true);
		}
	};

	// start the update manager and have it wait for us
	manager = new SwingUpdateManager(MIN_DELAY, MAX_DELAY, r);
	manager.update();

	// have the swing thread block until we countdown the end latch
	startLatch.await(10, TimeUnit.SECONDS);

	// post the second update request now that the manager is actively processing
	manager.update();

	// let the update manager finish; verify 2 work items total
	endLatch.countDown();
	waitForManager();
	assertEquals("Expected exactly 2 callbacks", 2, runnableCalled);
}
 
Example 11
/**
 * Ensures that any pending writes (such as those made via {@link Writer#apply()}) are finished.
 */
@AnyThread
synchronized void blockUntilAllWritesFinished() {
  CountDownLatch latch = new CountDownLatch(1);

  executor.execute(latch::countDown);

  try {
    latch.await();
  } catch (InterruptedException e) {
    Log.w(TAG, "Failed to wait for all writes.");
  }
}
 
Example 12
Source Project: kbear   File: ProducerTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void close(java.util.function.Consumer<Producer<String, String>> closer) throws InterruptedException {
    Properties properties = new Properties();
    properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    Producer<String, String> producer = getClientFactory().newProducer(properties);
    try {
        ExecutorService executorService = Executors.newFixedThreadPool(topics.size());
        AtomicInteger failedCount = new AtomicInteger();
        CountDownLatch latch = new CountDownLatch(topics.size());
        try {
            topics.forEach(t -> {
                executorService.submit(() -> {
                    try {
                        produceMessagesWithoutCallback(producer, t);
                    } catch (Throwable e) {
                        failedCount.incrementAndGet();
                        System.out.println("produce messages failed for " + t);
                        e.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                });
            });
        } finally {
            executorService.shutdown();
        }

        if (!latch.await(_waitTimeout, TimeUnit.MILLISECONDS))
            Assert.fail("produce message timeout: " + _waitTimeout);

        Assert.assertEquals(0, failedCount.get());

        checkOtherApis(producer);
    } finally {
        closer.accept(producer);
    }
}
 
Example 13
static NetworkManagementService create(Context context, String socket, SystemServices services)
        throws InterruptedException {
    final NetworkManagementService service =
            new NetworkManagementService(context, socket, services);
    final CountDownLatch connectedSignal = service.mConnectedSignal;
    if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
    service.mThread.start();
    if (DBG) Slog.d(TAG, "Awaiting socket connection");
    connectedSignal.await();
    if (DBG) Slog.d(TAG, "Connected");
    if (DBG) Slog.d(TAG, "Connecting native netd service");
    service.connectNativeNetdService();
    if (DBG) Slog.d(TAG, "Connected");
    return service;
}
 
Example 14
private void await(CountDownLatch latch) {
	try {
		latch.await(1000, TimeUnit.MILLISECONDS);
	}
	catch (InterruptedException ex) {
		throw new IllegalStateException(ex);
	}
	assertEquals("latch did not count down,", 0, latch.getCount());
}
 
Example 15
/**
 * Tests that the RPC service's scheduled executor service can execute runnables at a fixed
 * rate.
 */
@Test(timeout = 60000)
public void testScheduledExecutorServicePeriodicSchedule() throws Exception {
	ScheduledExecutor scheduledExecutor = akkaRpcService.getScheduledExecutor();

	final int tries = 4;
	final long delay = 10L;
	final CountDownLatch countDownLatch = new CountDownLatch(tries);

	long currentTime = System.nanoTime();

	ScheduledFuture<?> future = scheduledExecutor.scheduleAtFixedRate(
		countDownLatch::countDown,
		delay,
		delay,
		TimeUnit.MILLISECONDS);

	assertTrue(!future.isDone());

	countDownLatch.await();

	// the future should not complete since we have a periodic task
	assertTrue(!future.isDone());

	long finalTime = System.nanoTime() - currentTime;

	// the processing should have taken at least delay times the number of count downs.
	assertTrue(finalTime >= tries * delay);

	future.cancel(true);
}
 
Example 16
Source Project: Bats   File: Server.java    License: Apache License 2.0 5 votes vote down vote up
public InetSocketAddress run()
{
  final CountDownLatch latch = new CountDownLatch(1);
  this.latch = latch;
  eventloop.start(null, port, this);
  try {
    latch.await();
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
  return (InetSocketAddress)getServerAddress();
}
 
Example 17
/**
 * Called to start up the H2 database.
 *
 * @throws Exception
 */
public void start() throws Exception {
    PropertiesLoader properties = new PropertiesLoader();
    String jar = properties.get("h2.jar.file.path");
    String port = properties.get("h2.port");
    log.info(String.format("Starting H2 server: %s %s", jar, port));

    String[] cmdArray = {
            "java", "-cp", jar, "org.h2.tools.Server",
            "-tcp", "-tcpPort", port, "-tcpAllowOthers",
            "-ifNotExists"
    };

    log.info("H2 > " + Arrays.toString(cmdArray));

    process = Runtime.getRuntime().exec(cmdArray);
    InputStream is = process.getInputStream();
    InputStream err = process.getErrorStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    BufferedReader errReader = new BufferedReader(new InputStreamReader(err));
    List<String> msgs = new ArrayList<>();
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t = new Thread(() -> {
        try {
            String line;
            String errLine;
            while (process.isAlive()) {
                line = reader.readLine();
                if (line != null) {
                    log.info("H2 > " + line);
                    msgs.add(line);
                    if (line.contains("TCP server running")) {
                        log.info("H2 Server started ...");
                        latch.countDown();
                        return;
                    }
                }
                errLine = errReader.readLine();
                if (errLine != null) {
                    log.error("H2 err > " + errLine);
                    msgs.add("e: " + errLine);
                }
            }
            int exitValue = process.exitValue();
            if (exitValue == 0) {
                log.info("H2 Server process exited OK");
            } else {
                log.error("H2 Server process exited with error: " + exitValue + ", msgs: " + msgs);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        latch.countDown();
    }, "H2-thread");
    t.start();
    latch.await();
}
 
Example 18
Source Project: Flink-CEPplus   File: TaskExecutorTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Tests that offers slots to job master timeout and retry.
 */
@Test
public void testOfferSlotToJobMasterAfterTimeout() throws Exception {
	final TaskSlotTable taskSlotTable = new TaskSlotTable(
		Arrays.asList(ResourceProfile.UNKNOWN, ResourceProfile.UNKNOWN),
		timerService);
	final TaskManagerServices taskManagerServices = new TaskManagerServicesBuilder()
		.setTaskSlotTable(taskSlotTable)
		.build();

	final TaskExecutor taskExecutor = createTaskExecutor(taskManagerServices);

	final AllocationID allocationId = new AllocationID();

	final CompletableFuture<ResourceID> initialSlotReportFuture = new CompletableFuture<>();

	final TestingResourceManagerGateway testingResourceManagerGateway = new TestingResourceManagerGateway();
	testingResourceManagerGateway.setSendSlotReportFunction(resourceIDInstanceIDSlotReportTuple3 -> {
		initialSlotReportFuture.complete(null);
		return CompletableFuture.completedFuture(Acknowledge.get());

	});
	rpc.registerGateway(testingResourceManagerGateway.getAddress(), testingResourceManagerGateway);
	resourceManagerLeaderRetriever.notifyListener(testingResourceManagerGateway.getAddress(), testingResourceManagerGateway.getFencingToken().toUUID());

	final CountDownLatch slotOfferings = new CountDownLatch(3);
	final CompletableFuture<AllocationID> offeredSlotFuture = new CompletableFuture<>();
	final TestingJobMasterGateway jobMasterGateway = new TestingJobMasterGatewayBuilder()
		.setOfferSlotsFunction((resourceID, slotOffers) -> {
			assertThat(slotOffers.size(), is(1));
			slotOfferings.countDown();

			if (slotOfferings.getCount() == 0) {
				offeredSlotFuture.complete(slotOffers.iterator().next().getAllocationId());
				return CompletableFuture.completedFuture(slotOffers);
			} else {
				return FutureUtils.completedExceptionally(new TimeoutException());
			}
		})
		.build();
	final String jobManagerAddress = jobMasterGateway.getAddress();
	rpc.registerGateway(jobManagerAddress, jobMasterGateway);
	jobManagerLeaderRetriever.notifyListener(jobManagerAddress, jobMasterGateway.getFencingToken().toUUID());

	try {
		taskExecutor.start();
		final TaskExecutorGateway taskExecutorGateway = taskExecutor.getSelfGateway(TaskExecutorGateway.class);

		// wait for the connection to the ResourceManager
		initialSlotReportFuture.get();

		taskExecutorGateway.requestSlot(
			new SlotID(taskExecutor.getResourceID(), 0),
			jobId,
			allocationId,
			jobManagerAddress,
			testingResourceManagerGateway.getFencingToken(),
			timeout).get();

		slotOfferings.await();

		assertThat(offeredSlotFuture.get(), is(allocationId));
		assertTrue(taskSlotTable.isSlotFree(1));
	} finally {
		RpcUtils.terminateRpcEndpoint(taskExecutor, timeout);
	}
}
 
Example 19
Source Project: ghidra   File: SwingUpdateManagerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testIsBusy() throws Exception {
	//
	// Another complicated test: we want to make sure that if we try to trigger an update
	// that isBusy() will return true, even if the update runnable has not yet been posted
	// to the Swing thread.
	//
	// To do this, we will need to block the Swing thread so that we know the request happens
	// before the update runnable is called.
	//

	CountDownLatch startLatch = new CountDownLatch(1);
	CountDownLatch endLatch = new CountDownLatch(1);
	AtomicBoolean exception = new AtomicBoolean();

	runSwing(new Runnable() {
		@Override
		public void run() {
			startLatch.countDown();
			try {
				endLatch.await(10, TimeUnit.SECONDS);
			}
			catch (InterruptedException e) {
				exception.set(true);
			}
		}
	}, false);

	// This will cause the swing thread to block until we countdown the end latch
	startLatch.await(10, TimeUnit.SECONDS);

	manager.update();
	assertTrue("Manager not busy after requesting an update", manager.isBusy());

	endLatch.countDown();

	waitForManager();
	assertTrue("Manager still busy after waiting for update", !manager.isBusy());

	assertFalse("Interrupted waiting for CountDowLatch", exception.get());
}
 
Example 20
@Test
public void testDuplicateCancel() throws Exception {

	NettyServerAndClient serverAndClient = null;

	try {
		final TestPooledBufferProvider outboundBuffers = new TestPooledBufferProvider(16);

		ResultPartitionManager partitions = mock(ResultPartitionManager.class);

		ResultPartitionID pid = new ResultPartitionID();

		final CountDownLatch sync = new CountDownLatch(1);

		final ResultSubpartitionView view = spy(new InfiniteSubpartitionView(outboundBuffers, sync));

		// Return infinite subpartition
		when(partitions.createSubpartitionView(eq(pid), eq(0), any(BufferAvailabilityListener.class)))
				.thenAnswer(new Answer<ResultSubpartitionView>() {
					@Override
					public ResultSubpartitionView answer(InvocationOnMock invocationOnMock) throws Throwable {
						BufferAvailabilityListener listener = (BufferAvailabilityListener) invocationOnMock.getArguments()[2];
						listener.notifyDataAvailable();
						return view;
					}
				});

		NettyProtocol protocol = new NettyProtocol(
				partitions, mock(TaskEventDispatcher.class), true);

		serverAndClient = initServerAndClient(protocol);

		Channel ch = connect(serverAndClient);

		// Request for non-existing input channel => results in cancel request
		InputChannelID inputChannelId = new InputChannelID();

		ch.writeAndFlush(new PartitionRequest(pid, 0, inputChannelId, Integer.MAX_VALUE)).await();

		// Wait for the notification
		if (!sync.await(TestingUtils.TESTING_DURATION().toMillis(), TimeUnit.MILLISECONDS)) {
			fail("Timed out after waiting for " + TestingUtils.TESTING_DURATION().toMillis() +
					" ms to be notified about cancelled partition.");
		}

		ch.writeAndFlush(new CancelPartitionRequest(inputChannelId)).await();

		ch.close();

		NettyTestUtil.awaitClose(ch);

		verify(view, times(1)).releaseAllResources();
		verify(view, times(0)).notifySubpartitionConsumed();
	}
	finally {
		shutdown(serverAndClient);
	}
}