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

The following examples show how to use java.util.concurrent.CompletableFuture#runAsync() . 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: SysAttachSliceAppendUploader.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
/**
 * 生成完整附件(WEB端上传)
 * @return 返回生成的临时附件文件的ID
 */
@Override
public SysAttachUploadResultVO createFullAttach(SysAttachUploadSliceBaseVO sliceBaseVO,
                                                List<SysAttachFileSlice> sliceList, String summaryId) {
    SysAttachFileSlice currentSlice = sliceList.get(0);

    SysAttachUploadResultVO uploadResultVO = new SysAttachUploadResultVO();
    uploadResultVO.setFileId(currentSlice.getFdId());
    uploadResultVO.setFilePath(currentSlice.getFdFilePath());
    uploadResultVO.setFullPath(currentSlice.getFullPath());
    uploadResultVO.setSysAttachCatalog(currentSlice.getFdSysAttachCatalog());
    uploadResultVO.setSysAttachModuleLocation(currentSlice.getFdSysAttachModuleLocation());

    // 异步删除分片记录和分片概要
    CompletableFuture.runAsync(() -> {
        // 删除分片记录
        deleteSliceRecord(currentSlice.getFdId());
        // 删除分片概要
        deleteSliceSummary(summaryId);
    });

    return uploadResultVO;
}
 
Example 2
Source File: DefaultStreamExcelBuilderTest.java    From myexcel with Apache License 2.0 6 votes vote down vote up
private void data(DefaultStreamExcelBuilder<CommonPeople> excelBuilder, int size) {
    BigDecimal oddMoney = new BigDecimal(109898);
    BigDecimal evenMoney = new BigDecimal(66666);
    List<CompletableFuture> futures = new LinkedList<>();
    for (int i = 0; i < size; i++) {
        int index = i;
        CompletableFuture future = CompletableFuture.runAsync(() -> {
            CommonPeople commonPeople = new CommonPeople();
            boolean odd = index % 2 == 0;
            commonPeople.setName(odd ? "张三" : "李四");
            commonPeople.setAge(odd ? 18 : 24);
            commonPeople.setDance(odd ? true : false);
            commonPeople.setMoney(odd ? oddMoney : evenMoney);
            commonPeople.setBirthday(new Date());
            commonPeople.setLocalDate(LocalDate.now());
            commonPeople.setLocalDateTime(LocalDateTime.now());
            commonPeople.setCats(100L);
            excelBuilder.append(commonPeople);
        });
        futures.add(future);
    }
    futures.forEach(CompletableFuture::join);
}
 
Example 3
Source File: ShowTypingMiddleware.java    From botbuilder-java with MIT License 6 votes vote down vote up
private static CompletableFuture<Void> sendTyping(
    TurnContext turnContext,
    long delay,
    long period
) {
    return CompletableFuture.runAsync(() -> {
        try {
            Thread.sleep(delay);

            while (!Thread.currentThread().isInterrupted()) {
                sendTypingActivity(turnContext).join();
                Thread.sleep(period);
            }
        } catch (InterruptedException e) {
            // do nothing
        }
    }, ExecutorFactory.getExecutor());
}
 
Example 4
Source File: DirectoryService.java    From AsciidocFX with Apache License 2.0 6 votes vote down vote up
private Path workingDirectorySupplier() {

        if (!Platform.isFxApplicationThread()) {
            final CompletableFuture<Path> completableFuture = new CompletableFuture<>();
            completableFuture.runAsync(() -> {
                threadService.runActionLater(() -> {
                    try {
                        Path path = workingDirectorySupplier();
                        completableFuture.complete(path);
                    } catch (Exception e) {
                        completableFuture.completeExceptionally(e);
                    }
                });
            }, threadService.executor());
            return completableFuture.join();
        }

        final DirectoryChooser directoryChooser = newDirectoryChooser("Select working directory");
        final File file = directoryChooser.showDialog(null);

        workingDirectory = Optional.ofNullable(file.toPath());

        workingDirectory.ifPresent(fileBrowser::browse);

        return Objects.nonNull(file) ? file.toPath() : null;
    }
 
Example 5
Source File: JarDependenciesEndpoint.java    From Moss with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    CompletableFuture.runAsync(() -> {
        try {
            cachedObject = Analyzer.getAllPomInfo();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    });
}
 
Example 6
Source File: DefaultLanguageClient.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> registerCapability(RegistrationParams params) {
    return CompletableFuture.runAsync(() -> params.getRegistrations().forEach(r -> {
        String id = r.getId();
        Optional<DynamicRegistrationMethods> method = DynamicRegistrationMethods.forName(r.getMethod());
        method.ifPresent(dynamicRegistrationMethods -> registrations.put(id, dynamicRegistrationMethods));

    }));
}
 
Example 7
Source File: Issue298Test.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("FutureReturnValueIgnored")
public void readDuringCreate() {
  // Loaded value and waiting at expireAfterCreate (expire: infinite)
  cache.get(key);
  await().untilTrue(startedLoad);
  doLoad.set(true);
  await().untilTrue(startedCreate);

  // Async read trying to wait at expireAfterRead
  CompletableFuture<Void> reader = CompletableFuture.runAsync(() -> {
    do {
      cache.get(key);
    } while (!endRead.get());
  });

  // Ran expireAfterCreate (expire: infinite -> create)
  doCreate.set(true);
  await().until(() -> policy.getExpiresAfter(key).get().toNanos() <= EXPIRE_NS);
  await().untilTrue(startedRead);

  // Ran reader (expire: create -> ?)
  doRead.set(true);
  endRead.set(true);
  reader.join();

  // Ensure expire is [expireAfterCreate], not [infinite]
  assertThat(policy.getExpiresAfter(key).get().toNanos(), is(lessThanOrEqualTo(EXPIRE_NS)));
}
 
Example 8
Source File: ClientAdapterBase.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> createStream(String streamName, Duration timeout) {
    ensureRunning();
    return CompletableFuture.runAsync(() -> {
        if (this.streamWriters.containsKey(streamName)) {
            throw new CompletionException(new StreamSegmentExistsException(streamName));
        }

        StreamConfiguration config = StreamConfiguration
        .builder()
        .scalingPolicy(ScalingPolicy.fixed(this.testConfig.getSegmentsPerStream()))
                .build();
        if (!getStreamManager().createStream(SCOPE, streamName, config)) {
            throw new CompletionException(new StreamingException(String.format("Unable to create Stream '%s'.", streamName)));
        }

        List<EventStreamWriter<byte[]>> writers = new ArrayList<>(this.writersPerStream);
        if (this.streamWriters.putIfAbsent(streamName, writers) == null) {
            for (int i = 0; i < this.writersPerStream; i++) {
                writers.add(getClientFactory().createEventWriter(streamName, SERIALIZER, WRITER_CONFIG));
            }
        }
        List<TransactionalEventStreamWriter<byte[]>> txnWriters = new ArrayList<>(this.writersPerStream);
        if (this.transactionalWriters.putIfAbsent(streamName, txnWriters) == null) {
            for (int i = 0; i < this.writersPerStream; i++) {
                txnWriters.add(getClientFactory().createTransactionalEventWriter("writer", streamName, SERIALIZER, WRITER_CONFIG));
            }
        }
    }, this.testExecutor);
}
 
Example 9
Source File: TracedExecutorTest.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testExceptionThrownByExecutorShouldBeRethrownByTracedExecutor() {
  try {
    CompletableFuture.runAsync(
        () -> { },
        runtimeExceptionThrowingExecutor
    );
    fail();
  } catch (Exception ex) {
    assertEquals(RejectedExecutionException.class, ex.getClass());
    assertEquals(ex.getMessage(), "Some runtime exception thrown by executor.");
  }
}
 
Example 10
Source File: DistributedMeterStoreTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Test delete meter.
 */
@Test
public void testDeleteMeter() {
    // Init the store
    initMeterStore();
    // Simulate the allocation of an id
    MeterId idOne = meterStore.allocateMeterId(did1);
    // Verify the allocation
    assertThat(mid1, is(idOne));
    // Let's create a meter
    Meter meterOne = DefaultMeter.builder()
            .forDevice(did1)
            .fromApp(APP_ID)
            .withId(mid1)
            .withUnit(Meter.Unit.KB_PER_SEC)
            .withBands(Collections.singletonList(b1))
            .build();
    // Set the state
    ((DefaultMeter) meterOne).setState(MeterState.PENDING_ADD);
    // Store the meter
    meterStore.storeMeter(meterOne);
    // Set the state
    ((DefaultMeter) meterOne).setState(MeterState.PENDING_REMOVE);
    // Let's create meter key
    MeterKey meterKey = MeterKey.key(did1, mid1);
    // Delete meter
    meterStore.deleteMeter(meterOne);
    // Start an async delete, simulating the operation of the provider
    CompletableFuture<Void> future = CompletableFuture.runAsync(
            () -> meterStore.deleteMeterNow(meterOne)
    );
    // Let's wait
    try {
        future.get();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    // Verify delete
    assertThat(0, is(meterStore.getAllMeters().size()));
    assertThat(0, is(meterStore.getAllMeters(did1).size()));
    assertNull(meterStore.getMeter(meterKey));
    assertThat(mid1, is(meterStore.allocateMeterId(did1)));
}
 
Example 11
Source File: StreamTaskTerminationTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 * FLINK-6833
 *
 * <p>Tests that a finished stream task cannot be failed by an asynchronous checkpointing operation after
 * the stream task has stopped running.
 */
@Test
public void testConcurrentAsyncCheckpointCannotFailFinishedStreamTask() throws Exception {
	final Configuration taskConfiguration = new Configuration();
	final StreamConfig streamConfig = new StreamConfig(taskConfiguration);
	final NoOpStreamOperator<Long> noOpStreamOperator = new NoOpStreamOperator<>();

	final StateBackend blockingStateBackend = new BlockingStateBackend();

	streamConfig.setStreamOperator(noOpStreamOperator);
	streamConfig.setOperatorID(new OperatorID());
	streamConfig.setStateBackend(blockingStateBackend);

	final long checkpointId = 0L;
	final long checkpointTimestamp = 0L;

	final JobInformation jobInformation = new JobInformation(
		new JobID(),
		"Test Job",
		new SerializedValue<>(new ExecutionConfig()),
		new Configuration(),
		Collections.emptyList(),
		Collections.emptyList());

	final TaskInformation taskInformation = new TaskInformation(
		new JobVertexID(),
		"Test Task",
		1,
		1,
		BlockingStreamTask.class.getName(),
		taskConfiguration);

	final TaskManagerRuntimeInfo taskManagerRuntimeInfo = new TestingTaskManagerRuntimeInfo();

	TaskEventDispatcher taskEventDispatcher = new TaskEventDispatcher();
	final NetworkEnvironment networkEnv = mock(NetworkEnvironment.class);
	when(networkEnv.createKvStateTaskRegistry(any(JobID.class), any(JobVertexID.class))).thenReturn(mock(TaskKvStateRegistry.class));
	when(networkEnv.getTaskEventDispatcher()).thenReturn(taskEventDispatcher);

	BlobCacheService blobService =
		new BlobCacheService(mock(PermanentBlobCache.class), mock(TransientBlobCache.class));

	final Task task = new Task(
		jobInformation,
		taskInformation,
		new ExecutionAttemptID(),
		new AllocationID(),
		0,
		0,
		Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
		Collections.<InputGateDeploymentDescriptor>emptyList(),
		0,
		new MemoryManager(32L * 1024L, 1),
		new IOManagerAsync(),
		networkEnv,
		mock(BroadcastVariableManager.class),
		new TestTaskStateManager(),
		mock(TaskManagerActions.class),
		mock(InputSplitProvider.class),
		mock(CheckpointResponder.class),
		new TestGlobalAggregateManager(),
		blobService,
		new BlobLibraryCacheManager(
			blobService.getPermanentBlobService(),
			FlinkUserCodeClassLoaders.ResolveOrder.CHILD_FIRST,
			new String[0]),
		mock(FileCache.class),
		taskManagerRuntimeInfo,
		UnregisteredMetricGroups.createUnregisteredTaskMetricGroup(),
		new NoOpResultPartitionConsumableNotifier(),
		mock(PartitionProducerStateChecker.class),
		Executors.directExecutor());

	CompletableFuture<Void> taskRun = CompletableFuture.runAsync(
		() -> task.run(),
		TestingUtils.defaultExecutor());

	// wait until the stream task started running
	RUN_LATCH.await();

	// trigger a checkpoint
	task.triggerCheckpointBarrier(checkpointId, checkpointTimestamp, CheckpointOptions.forCheckpointWithDefaultLocation());

	// wait until the task has completed execution
	taskRun.get();

	// check that no failure occurred
	if (task.getFailureCause() != null) {
		throw new Exception("Task failed", task.getFailureCause());
	}

	// check that we have entered the finished state
	assertEquals(ExecutionState.FINISHED, task.getExecutionState());
}
 
Example 12
Source File: SubscriberBeanWithMethodsReturningCompletionStage.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Incoming(PRE_PROCESSING_ACKNOWLEDGMENT_MESSAGE)
@Acknowledgment(Acknowledgment.Strategy.PRE_PROCESSING)
public CompletionStage<Void> preProcessingWithMessage(Message<String> message) {
    return CompletableFuture.runAsync(() -> processed(PRE_PROCESSING_ACKNOWLEDGMENT_MESSAGE, message), EXECUTOR);
}
 
Example 13
Source File: BookKeeperLog.java    From pravega with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Void> truncate(LogAddress upToAddress, Duration timeout) {
    ensurePreconditions();
    Preconditions.checkArgument(upToAddress instanceof LedgerAddress, "upToAddress must be of type LedgerAddress.");
    return CompletableFuture.runAsync(() -> tryTruncate((LedgerAddress) upToAddress), this.executorService);
}
 
Example 14
Source File: ApiActionLogger.java    From LuckPerms with MIT License 4 votes vote down vote up
@Override
public @NonNull CompletableFuture<Void> submit(@NonNull Action entry) {
    return CompletableFuture.runAsync(() -> this.plugin.getLogDispatcher().dispatchFromApi((LoggedAction) entry), this.plugin.getBootstrap().getScheduler().async());
}
 
Example 15
Source File: SubscriberBeanWithMethodsReturningCompletionStage.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Incoming(POST_PROCESSING_ACKNOWLEDGMENT_PAYLOAD)
@Acknowledgment(Acknowledgment.Strategy.POST_PROCESSING)
public CompletionStage<Void> postProcessingWithPayload(String payload) {
    return CompletableFuture.runAsync(() -> processed(POST_PROCESSING_ACKNOWLEDGMENT_PAYLOAD, payload), EXECUTOR);
}
 
Example 16
Source File: TableStoreMock.java    From pravega with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Void> remove(String segmentName, Collection<TableKey> keys, Duration timeout) {
    Exceptions.checkNotClosed(this.closed.get(), this);
    return CompletableFuture.runAsync(() -> getTableData(segmentName).remove(keys), this.executor);
}
 
Example 17
Source File: DirectoryService.java    From AsciidocFX with Apache License 2.0 4 votes vote down vote up
public Path getSaveOutputPath(FileChooser.ExtensionFilter extensionFilter, boolean askPath) {

        if (!Platform.isFxApplicationThread()) {
            final CompletableFuture<Path> completableFuture = new CompletableFuture<>();

            completableFuture.runAsync(() -> {
                threadService.runActionLater(() -> {
                    try {
                        Path outputPath = getSaveOutputPath(extensionFilter, askPath);
                        completableFuture.complete(outputPath);
                    } catch (Exception e) {
                        completableFuture.completeExceptionally(e);
                    }
                });
            }, threadService.executor());

            return completableFuture.join();
        }

        boolean isNew = current.currentTab().isNew();

        if (isNew) {
            controller.saveDoc();
        }

        final Path currentTabPath = current.currentPath().get();
        final Path currentTabPathDir = currentTabPath.getParent();
        String tabText = current.getCurrentTabText().replace("*", "").trim();
        tabText = tabText.contains(".") ? tabText.split("\\.")[0] : tabText;

        if (!askPath) {
            return currentTabPathDir.resolve(extensionFilter.getExtensions().get(0).replace("*", tabText));
        }

        final FileChooser fileChooser = this.newFileChooser(String.format("Save %s file", extensionFilter.getDescription()));
        fileChooser.getExtensionFilters().addAll(extensionFilter);
        File file = fileChooser.showSaveDialog(null);

        if (Objects.isNull(file)) {
            return currentTabPathDir.resolve(extensionFilter.getExtensions().get(0).replace("*", tabText));
        }

        return file.toPath();
    }
 
Example 18
Source File: VRPlatform.java    From ViaFabric with MIT License 4 votes vote down vote up
private TaskId runServerSync(Runnable runnable) {
    // Kick task needs to be on main thread, it does already have error logger
    return new FutureTaskId(CompletableFuture.runAsync(runnable, getServer()));
}
 
Example 19
Source File: FabricPipeliner.java    From onos with Apache License 2.0 4 votes vote down vote up
private void success(Objective objective) {
    CompletableFuture.runAsync(
            () -> objective.context().ifPresent(
                    ctx -> ctx.onSuccess(objective)), callbackExecutor);
}
 
Example 20
Source File: WorkspaceSharedPool.java    From che with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Asynchronously runs the given task wrapping it with {@link
 * ThreadLocalPropagateContext#wrap(Runnable)}
 *
 * @param runnable task to run
 * @return completable future bounded to the task
 */
public CompletableFuture<Void> runAsync(Runnable runnable) {
  return CompletableFuture.runAsync(ThreadLocalPropagateContext.wrap(runnable), executor);
}