Java Code Examples for java.util.concurrent.CompletableFuture#thenRunAsync()

The following examples show how to use java.util.concurrent.CompletableFuture#thenRunAsync() . 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: Dispatcher.java    From flink with Apache License 2.0 6 votes vote down vote up
private void registerJobManagerRunnerTerminationFuture(JobID jobId, CompletableFuture<Void> jobManagerRunnerTerminationFuture) {
	Preconditions.checkState(!jobManagerTerminationFutures.containsKey(jobId));

	jobManagerTerminationFutures.put(jobId, jobManagerRunnerTerminationFuture);

	// clean up the pending termination future
	jobManagerRunnerTerminationFuture.thenRunAsync(
		() -> {
			final CompletableFuture<Void> terminationFuture = jobManagerTerminationFutures.remove(jobId);

			//noinspection ObjectEquality
			if (terminationFuture != null && terminationFuture != jobManagerRunnerTerminationFuture) {
				jobManagerTerminationFutures.put(jobId, terminationFuture);
			}
		},
		getMainThreadExecutor());
}
 
Example 2
Source File: Dispatcher.java    From flink with Apache License 2.0 6 votes vote down vote up
private void registerJobManagerRunnerTerminationFuture(JobID jobId, CompletableFuture<Void> jobManagerRunnerTerminationFuture) {
	Preconditions.checkState(!jobManagerTerminationFutures.containsKey(jobId));

	jobManagerTerminationFutures.put(jobId, jobManagerRunnerTerminationFuture);

	// clean up the pending termination future
	jobManagerRunnerTerminationFuture.thenRunAsync(
		() -> {
			final CompletableFuture<Void> terminationFuture = jobManagerTerminationFutures.remove(jobId);

			//noinspection ObjectEquality
			if (terminationFuture != null && terminationFuture != jobManagerRunnerTerminationFuture) {
				jobManagerTerminationFutures.put(jobId, terminationFuture);
			}
		},
		getUnfencedMainThreadExecutor());
}
 
Example 3
Source File: TestOrdersGenerator.java    From exchange-core with Apache License 2.0 6 votes vote down vote up
private static CompletableFuture<List<ApiCommand>> mergeCommands(
        Map<Integer, GenResult> genResults,
        long seed,
        boolean takeBenchmark,
        CompletableFuture<?> runAfterThis) {

    final List<List<OrderCommand>> commandsLists = genResults.values().stream()
            .map(genResult -> takeBenchmark ? genResult.commandsBenchmark : genResult.commandsFill)
            .collect(Collectors.toList());

    log.debug("Merging {} commands for {} symbols ({})...",
            commandsLists.stream().mapToInt(Collection::size).sum(), genResults.size(), takeBenchmark ? "benchmark" : "preFill");

    final List<OrderCommand> merged = RandomCollectionsMerger.mergeCollections(commandsLists, seed);

    final CompletableFuture<List<ApiCommand>> resultFuture = runAfterThis.thenApplyAsync(ignore -> TestOrdersGenerator.convertToApiCommand(merged));

    if (takeBenchmark) {
        resultFuture.thenRunAsync(() -> printStatistics(merged));
    }

    return resultFuture;
}
 
Example 4
Source File: JavaAsyncFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensureConstN() throws InterruptedException, ExecutionException {
  CompletableFuture<Void> f = constVoidFuture;
  for (int i = 0; i < N.n; i++)
    f = f.thenRunAsync(ensureF);
  return f.get();
}
 
Example 5
Source File: PrimaryBackupServiceContext.java    From atomix with Apache License 2.0 5 votes vote down vote up
/**
 * Closes the service.
 */
public CompletableFuture<Void> close() {
  CompletableFuture<Void> future = new CompletableFuture<>();
  threadContext.execute(() -> {
    try {
      clusterMembershipService.removeListener(membershipEventListener);
      primaryElection.removeListener(primaryElectionListener);
      role.close();
    } finally {
      future.complete(null);
    }
  });
  return future.thenRunAsync(() -> threadContext.close());
}
 
Example 6
Source File: JavaAsyncFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensurePromiseN() throws InterruptedException, ExecutionException {
  CompletableFuture<Void> p = new CompletableFuture<>();
  CompletableFuture<Void> f = p;
  for (int i = 0; i < N.n; i++)
    f = f.thenRunAsync(ensureF);
  p.complete(null);
  return f.get();
}
 
Example 7
Source File: JavaAsyncFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensurePromise() throws InterruptedException, ExecutionException {
  CompletableFuture<Void> p = new CompletableFuture<Void>();
  CompletableFuture<Void> f = p.thenRunAsync(ensureF);
  p.complete(null);
  return f.get();
}
 
Example 8
Source File: JavaAsyncFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensureConstN() throws InterruptedException, ExecutionException {
  CompletableFuture<Void> f = constVoidFuture;
  for (int i = 0; i < N.n; i++)
    f = f.thenRunAsync(ensureF);
  return f.get();
}
 
Example 9
Source File: JavaAsyncFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensurePromiseN() throws InterruptedException, ExecutionException {
  CompletableFuture<Void> p = new CompletableFuture<>();
  CompletableFuture<Void> f = p;
  for (int i = 0; i < N.n; i++)
    f = f.thenRunAsync(ensureF);
  p.complete(null);
  return f.get();
}
 
Example 10
Source File: JavaAsyncFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensurePromise() throws InterruptedException, ExecutionException {
  CompletableFuture<Void> p = new CompletableFuture<Void>();
  CompletableFuture<Void> f = p.thenRunAsync(ensureF);
  p.complete(null);
  return f.get();
}
 
Example 11
Source File: DependencyTaskExecutor.java    From interview with Apache License 2.0 5 votes vote down vote up
void scheduleTask(List<Task> tasks, int threads) {
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    CompletableFuture<Void> future = CompletableFuture.completedFuture(null);
    for (Task task : tasks) {
        future = future.thenAcceptBothAsync(scheduleTaskUtil(task, executor), (a, b) -> {}, executor);
    }
    future.thenRunAsync(() -> {System.out.println("All tasks done. Closing executor"); executor.shutdown();});
}
 
Example 12
Source File: Dispatcher.java    From flink with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<Void> removeJob(JobID jobId, boolean cleanupHA) {
	CompletableFuture<JobManagerRunner> jobManagerRunnerFuture = jobManagerRunnerFutures.remove(jobId);

	final CompletableFuture<Void> jobManagerRunnerTerminationFuture;
	if (jobManagerRunnerFuture != null) {
		jobManagerRunnerTerminationFuture = jobManagerRunnerFuture.thenCompose(JobManagerRunner::closeAsync);
	} else {
		jobManagerRunnerTerminationFuture = CompletableFuture.completedFuture(null);
	}

	return jobManagerRunnerTerminationFuture.thenRunAsync(
		() -> cleanUpJobData(jobId, cleanupHA),
		getRpcService().getExecutor());
}
 
Example 13
Source File: SupplyAsyncTest.java    From hellokoding-courses with MIT License 5 votes vote down vote up
@Test
public void thenRunAsync() throws ExecutionException, InterruptedException {
    CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Future");

    completableFuture = completableFuture.thenApplyAsync((s) -> s.concat(" is awesome!"));
    CompletableFuture<Void> procedureFuture = completableFuture.thenRunAsync(() -> System.out.println("!"));

    assertThat(procedureFuture.get()).isNull();
}
 
Example 14
Source File: Dispatcher.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<Void> removeJob(JobID jobId, boolean cleanupHA) {
	CompletableFuture<JobManagerRunner> jobManagerRunnerFuture = jobManagerRunnerFutures.remove(jobId);

	final CompletableFuture<Void> jobManagerRunnerTerminationFuture;
	if (jobManagerRunnerFuture != null) {
		jobManagerRunnerTerminationFuture = jobManagerRunnerFuture.thenCompose(JobManagerRunner::closeAsync);
	} else {
		jobManagerRunnerTerminationFuture = CompletableFuture.completedFuture(null);
	}

	return jobManagerRunnerTerminationFuture.thenRunAsync(
		() -> cleanUpJobData(jobId, cleanupHA),
		getRpcService().getExecutor());
}
 
Example 15
Source File: CompletableFutureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public <T> CompletableFuture<Void> thenRun
    (CompletableFuture<T> f, Runnable a) {
    return f.thenRunAsync(a, new ThreadExecutor());
}
 
Example 16
Source File: CompletableFutureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public <T> CompletableFuture<Void> thenRun
    (CompletableFuture<T> f, Runnable a) {
    return f.thenRunAsync(a);
}
 
Example 17
Source File: ManagedExecutorTest.java    From microprofile-context-propagation with Apache License 2.0 4 votes vote down vote up
/**
 * When an already-contextualized Runnable is specified as the action/task,
 * the action/task runs with its already-captured context rather than
 * capturing and applying context per the configuration of the managed executor.
 *
 * @throws ExecutionException indicates test failure
 * @throws InterruptedException indicates test failure
 * @throws TimeoutException indicates test failure
 */
@Test
public void contextOfContextualRunnableOverridesContextOfManagedExecutor() throws ExecutionException, InterruptedException, TimeoutException {
    ThreadContext labelContext = ThreadContext.builder()
            .propagated(Label.CONTEXT_NAME)
            .unchanged()
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    ManagedExecutor executor = ManagedExecutor.builder()
            .propagated(Buffer.CONTEXT_NAME)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();
    try {
        Buffer.set(new StringBuffer("contextualRunnableOverride-buffer-1"));
        Label.set("contextualRunnableOverride-label-1");

        Runnable precontextualizedTask1 = labelContext.contextualRunnable(() -> {
            Assert.assertEquals(Label.get(), "contextualRunnableOverride-label-1",
                    "Previously captured context type not found on thread.");
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type not cleared from thread.");
        });

        Buffer.set(new StringBuffer("contextualRunnableOverride-buffer-2"));
        Label.set("contextualRunnableOverride-label-2");

        Runnable precontextualizedTask2 = labelContext.contextualRunnable(() -> {
            Assert.assertEquals(Label.get(), "contextualRunnableOverride-label-2",
                    "Previously captured context type not found on thread.");
            Assert.assertEquals(Buffer.get().toString(), "",
                    "Context type not cleared from thread.");
        });

        Buffer.set(new StringBuffer("contextualRunnableOverride-buffer-3"));
        Label.set("contextualRunnableOverride-label-3");

        Runnable normalTask = () -> {
            Assert.assertEquals(Buffer.get().toString(), "contextualRunnableOverride-buffer-3",
                    "Previously captured context type not found on thread.");
            Assert.assertEquals(Label.get(), "",
                    "Context type not cleared from thread.");
        };

        Future<Integer> future = executor.submit(precontextualizedTask1, 1);
        Assert.assertEquals(future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Integer.valueOf(1),
                "Unexpected result of task.");

        CompletableFuture<Void> stage0 = executor.runAsync(precontextualizedTask1);
        CompletableFuture<Void> stage1 = stage0.thenRunAsync(precontextualizedTask1);
        CompletableFuture<Void> stage2 = stage0.thenRun(precontextualizedTask2);
        CompletableFuture<Void> stage3 = stage1.runAfterEither(stage2, precontextualizedTask2);
        CompletableFuture<Void> stage4 = stage1.runAfterBothAsync(stage2, precontextualizedTask1);
        CompletableFuture<Void> stage5 = stage4.runAfterBoth(stage3, normalTask);
        stage5.join();

        LinkedBlockingQueue<String> results = new LinkedBlockingQueue<String>();
        Runnable precontextualizedTask3 = labelContext.contextualRunnable(() -> results.add(Label.get()));

        Buffer.set(new StringBuffer("contextualRunnableOverride-buffer-4"));
        Label.set("contextualRunnableOverride-label-4");

        executor.execute(precontextualizedTask3);
        Assert.assertEquals(results.poll(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "contextualRunnableOverride-label-3",
                "Previously captured context type not found on thread.");
    }
    finally {
        executor.shutdownNow();
        // Restore original values
        Buffer.set(null);
        Label.set(null);
    }
}
 
Example 18
Source File: SpillableSubpartitionTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 * Tests a fix for FLINK-12544.
 *
 * @see <a href="https://issues.apache.org/jira/browse/FLINK-12544">FLINK-12544</a>
 */
@Test
public void testConcurrentRequestAndReleaseMemory() throws Exception {
	final ExecutorService executor = Executors.newFixedThreadPool(2);
	final NetworkBufferPool networkBufferPool = new NetworkBufferPool(10, 32);
	try {
		final CountDownLatch blockLatch = new CountDownLatch(1);
		final CountDownLatch doneLatch = new CountDownLatch(1);

		final IOManager ioManager = new IOManagerAsyncWithCountDownLatch(blockLatch, doneLatch);
		final ResultPartitionWithCountDownLatch partition = new ResultPartitionWithCountDownLatch(
			"Test",
			new NoOpTaskActions(),
			new JobID(),
			new ResultPartitionID(),
			ResultPartitionType.BLOCKING,
			1,
			1,
			new ResultPartitionManager(),
			new NoOpResultPartitionConsumableNotifier(),
			ioManager,
			true,
			doneLatch,
			blockLatch);
		final BufferPool bufferPool = networkBufferPool.createBufferPool(1, 1, Optional.of(partition));
		partition.registerBufferPool(bufferPool);

		final BufferBuilder firstBuffer = bufferPool.requestBufferBuilderBlocking();
		partition.addBufferConsumer(firstBuffer.createBufferConsumer(), 0);
		// Finishes the buffer consumer which could be recycled during SpillableSubpartition#releaseMemory
		firstBuffer.finish();

		Future<Void> future = executor.submit(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				//Occupies the lock in SpillableSubpartition#releaseMemory, trying to get the lock in LocalBufferPool#recycle
				partition.releaseMemory(1);
				return null;
			}
		});

		final CompletableFuture<?> firstCallFuture = partition.getFirstCallFuture();
		firstCallFuture.thenRunAsync(() -> {
			try {
				// There are no available buffers in pool, so trigger release memory in SpillableSubpartition.
				// Occupies the lock in LocalBufferPool, and trying to get the lock in SpillableSubpartition.
				BufferBuilder secondBuffer = bufferPool.requestBufferBuilderBlocking();

				assertThat(firstBuffer, is(equalTo(secondBuffer)));
			} catch (IOException | InterruptedException ex) {
				fail("Should not throw any exceptions!");
			}
		}, executor);

		future.get();
	} finally {
		networkBufferPool.destroyAllBufferPools();
		networkBufferPool.destroy();
		executor.shutdown();
	}
}
 
Example 19
Source File: CompletableFutureTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public <T> CompletableFuture<Void> thenRun
    (CompletableFuture<T> f, Runnable a) {
    return f.thenRunAsync(a);
}
 
Example 20
Source File: CompletableFutureTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public <T> CompletableFuture<Void> thenRun
    (CompletableFuture<T> f, Runnable a) {
    return f.thenRunAsync(a, new ThreadExecutor());
}