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

The following examples show how to use java.util.concurrent.CountDownLatch#await() . 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: PrometheusMain.java    From tunnel with 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 File: TestUtils.java    From waltz with 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 3
Source File: SignleTaskStartEngine.java    From qmcflactomp3 with GNU General Public License v3.0 6 votes vote down vote up
@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 4
Source File: CheckOutThreadTest.java    From Tomcat8-Source-Read with 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 5
Source File: LazyBuilderTest.java    From jkube with 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 6
Source File: ReactorNettyTcpStompClientTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 7
Source File: DateFormatExample2.java    From Project with 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 8
Source File: EmbeddedChannelTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@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 9
Source File: LRUCacheTest.java    From smallrye-graphql with 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 10
Source File: ProducerTest.java    From kbear with 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 11
Source File: KeyValueStore.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 File: NetworkManagementService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
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 13
Source File: AbstractSchedulingTaskExecutorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
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 14
Source File: AkkaRpcServiceTest.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * 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 15
Source File: Server.java    From Bats with 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 16
Source File: SwingUpdateManagerTest.java    From ghidra with 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 17
Source File: TaskExecutorTest.java    From Flink-CEPplus with 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 18
Source File: SwingUpdateManagerTest.java    From ghidra with 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 19
Source File: H2DatabaseService.java    From apicurio-registry with Apache License 2.0 4 votes vote down vote up
/**
 * 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 20
Source File: CancelPartitionRequestTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@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);
	}
}