本文整理汇总了Java中java.util.concurrent.CompletableFuture.supplyAsync方法的典型用法代码示例。如果您正苦于以下问题:Java CompletableFuture.supplyAsync方法的具体用法?Java CompletableFuture.supplyAsync怎么用?Java CompletableFuture.supplyAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.CompletableFuture
的用法示例。
在下文中一共展示了CompletableFuture.supplyAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: loadConfig
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private CompletableFuture<List<KeyValueConfigEntity>> loadConfig(KeyValueConfigName configName) {
return CompletableFuture.supplyAsync(() -> {
List<KeyValueConfigEntity> result;
try {
result = repository.findAll(configName);
} catch (Exception e) {
LOGGER.warn("Exception at {}.findAll({}), cause: {}", repository.getClass().getSimpleName(), configName, e);
result = Collections.emptyList();
}
return result;
}, executor);
}
示例2: executeAsync
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* This interface is typically used to operations like
* `click`, `clear`, `readText` and so on
*
* @param o asynchronous operation to be performed
* @param w webelement on which the operation must be performed
* @return CompletableFuture<WebElement>
*
* E.g. TestExecutionController tec = new TestExecutionController(...)
* WebElement zip_code = pageObject.zip_code;
* String[] zip = {"90210"};
* tec.executeAsync(AsyncPageOperationsAdapter.clear, zip_code)
.thenApply(w -> tec.executeAsync(AsyncPageOperationsAdapter.putText, (WebElement)w, zip));
*/
public CompletableFuture<WebElement> executeAsync(asyncOpOnWebElement o, WebElement w) {
startTime();
CompletableFuture<WebElement> a = CompletableFuture.supplyAsync(() -> {
try{
o.on(currentPage, w);
}
catch(Exception e)
{
e.printStackTrace();
}
return w;
});
futures.add(a);
return a;
}
示例3: deleteLastMessages
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private void deleteLastMessages(CommandContext context, int limit) {
int maxDepth = 1000;
limit = Math.min(maxDepth, limit);
IMessage message = context.getMessage();
IDiscordClient client = message.getClient();
IChannel c = client.getChannelByID(message.getChannel().getLongID());
if (c != null) {
log.info("Preparing to delete latest {} to channel {}", inflect(limit, "bot message"), c.getName());
int deleted = 0;
int i = 0;
List<IMessage> toDelete = new ArrayList<>();
MessageHistory history = c.getMessageHistory(limit);
while (deleted < limit && i < history.size()) {
IMessage msg = history.get(i++);
if (msg.getAuthor().equals(client.getOurUser())) {
toDelete.add(msg);
deleted++;
}
}
if (c.isPrivate() || toDelete.size() == 1) {
AtomicBoolean abort = new AtomicBoolean(false);
for (IMessage delete : toDelete) {
if (abort.get()) {
break;
}
RequestBuffer.request(() -> {
try {
delete.delete();
} catch (MissingPermissionsException | DiscordException e) {
log.warn("Could not delete message - aborting", e);
abort.set(true);
}
}).get();
}
} else {
CompletableFuture.supplyAsync(() -> deleteInBatch(c, toDelete));
}
}
}
示例4: should_allow_composition_of_data_loader_calls
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Test
public void should_allow_composition_of_data_loader_calls() throws Exception {
UserManager userManager = new UserManager();
BatchLoader<Long, User> userBatchLoader = userIds -> CompletableFuture
.supplyAsync(() -> userIds
.stream()
.map(userManager::loadUserById)
.collect(Collectors.toList()));
DataLoader<Long, User> userLoader = new DataLoader<>(userBatchLoader);
AtomicBoolean gandalfCalled = new AtomicBoolean(false);
AtomicBoolean sarumanCalled = new AtomicBoolean(false);
userLoader.load(1L)
.thenAccept(user -> userLoader.load(user.getInvitedByID())
.thenAccept(invitedBy -> {
gandalfCalled.set(true);
assertThat(invitedBy.getName(), equalTo("Manwë"));
}));
userLoader.load(2L)
.thenAccept(user -> userLoader.load(user.getInvitedByID())
.thenAccept(invitedBy -> {
sarumanCalled.set(true);
assertThat(invitedBy.getName(), equalTo("Aulë"));
}));
List<User> allResults = userLoader.dispatchAndJoin();
await().untilTrue(gandalfCalled);
await().untilTrue(sarumanCalled);
assertThat(allResults.size(), equalTo(4));
}
示例5: connect
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* Create new session factory bean for provided cassandra endpoint
*
* @param connectionData connection metadata
* @return future providing new instance of {@link CassandraAdminTemplate template} to manage cassandra data
*/
public CompletableFuture<CassandraAdminTemplate> connect(ConnectionData connectionData) {
return CompletableFuture.supplyAsync(() -> {
if (isNullOrEmpty(connectionData.getKeyspace()) || isNullOrEmpty(connectionData.getUrl())) {
throw new UrlSyntaxException("Both url and keyspace are required");
}
String[] urlParts = connectionData.getUrl().split(":");
if (urlParts.length != 2) {
throw new UrlSyntaxException("Url should contain host:port");
}
int port;
try {
port = Integer.parseInt(urlParts[1]);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new UrlSyntaxException("Invalid port : " + urlParts[1]);
}
Cluster.Builder builder = Cluster.builder()
.addContactPoint(urlParts[0])
.withPort(port);
if (StringUtils.isNoneBlank(connectionData.getUsername(), connectionData.getPassword())) {
builder.withCredentials(connectionData.getUsername(), connectionData.getPassword());
}
Cluster cluster = builder.build();
CassandraSessionFactoryBean factory =
beanFactory.getBean(CassandraSessionFactoryBean.class, cluster, connectionData.getKeyspace());
Field adminTemplateField = findField(CassandraSessionFactoryBean.class, "admin");
adminTemplateField.setAccessible(true);
CassandraAdminTemplate template = (CassandraAdminTemplate) getField(adminTemplateField, factory);
this.template.set(template);
return template;
});
}
示例6: testBehaviorOfIteratorsCycleWhenAddingNewKey
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* Just a sanity test of java behaviors.
* - Create a concurrent hashmap with 4 entries
* - Create a new thread that runs forever cycling over the keys
* - In main thread add a new key.
* - See what happens to the thread cycling over keys, it should show up.
*/
@Test
public void testBehaviorOfIteratorsCycleWhenAddingNewKey() throws ExecutionException, InterruptedException {
final Map<String, String> myMap = Maps.newConcurrentMap();
myMap.put("Key1", "Value1");
myMap.put("Key2", "Value2");
myMap.put("Key3", "Value3");
myMap.put("Key4", "Value4");
// Create new Thread
final CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
Iterator<String> keyIterator = Iterators.cycle(myMap.keySet());
while (keyIterator.hasNext()) {
final String keyValue = keyIterator.next();
if (keyValue.equals("Key5")) {
return keyValue;
}
}
return "Nada";
});
// Wait for a few iterations in the other thread have completed.
Thread.sleep(1000L);
// Modify the keys, adding a new one
myMap.put("Key5", "Value5");
// Make sure we get it.
await()
.atMost(5, TimeUnit.SECONDS)
.until(() -> {
// Ask for next tuple
return future.getNow("NotYet");
}, equalTo("Key5"));
}
示例7: loadDatabasePropertiesIntoMemory
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private CompletableFuture<DatabaseProperties> loadDatabasePropertiesIntoMemory(final MessageReceivedEvent event) {
return CompletableFuture.supplyAsync(() -> {
if (!event.getChannelType().isGuild()) {
return new DatabaseProperties(null, null);
}
GuildTransformer guild = GuildController.fetchGuild(avaire, event.getMessage());
if (guild == null || !guild.isLevels()) {
return new DatabaseProperties(guild, null);
}
return new DatabaseProperties(guild, PlayerController.fetchPlayer(avaire, event.getMessage()));
});
}
示例8: abortLRA
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private void abortLRA() {
int status = status();
if (status == ActionStatus.RUNNING || status == ActionStatus.ABORT_ONLY) {
if (LRALogger.logger.isDebugEnabled()) {
LRALogger.logger.debugf("Transaction.abortLRA cancelling LRA %s", id);
}
CompletableFuture.supplyAsync(this::cancelLRA); // use a future to avoid hogging the ScheduledExecutorService
}
}
示例9: getTransactionRequestAsync
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<GetTransactionRequestResponseVO[]> getTransactionRequestAsync(final GetTransactionRequestRequestVO request) {
return CompletableFuture.supplyAsync(() -> getTransactionRequest(request), getExecutorService());
}
示例10: executeAsync
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
public <T> CompletableFuture<BeanSearchResult<T>> executeAsync(FulltextSearch search, Class<T> c, Executor executor) {
return CompletableFuture.supplyAsync(() -> this.execute(search, c), executor);
}
示例11: personNamesAsync
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@GetMapping("/api/peopleAsync")
public CompletableFuture<Collection<String>> personNamesAsync() {
return CompletableFuture.supplyAsync(() -> Collections.singletonList("jon"));
}
示例12: execute
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
public CompletableFuture<ResultSet> execute(String cql) {
return CompletableFuture.supplyAsync(() -> template.get().query(cql));
}
示例13: createIdentityAsync
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<CreateIdentityResponseVO> createIdentityAsync(final CreateIdentityRequestVO request) {
return CompletableFuture.supplyAsync(() -> createIdentity(request), getExecutorService());
}
示例14: getAll
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
public CompletableFuture<ResultSet> getAll(String table) {
return CompletableFuture.supplyAsync(() -> template.get().query(NStrings.format("select * from {}", table)));
}
示例15: getIdentityAsync
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<GetIdentityResponseVO[]> getIdentityAsync(final GetIdentityRequestVO request) {
return CompletableFuture.supplyAsync(() -> getIdentity(request), getExecutorService());
}