当前位置: 首页>>代码示例>>Java>>正文


Java CompletableFuture.supplyAsync方法代码示例

本文整理汇总了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);
}
 
开发者ID:scalecube,项目名称:config,代码行数:13,代码来源:KeyValueConfigSource.java

示例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;
}
 
开发者ID:saiscode,项目名称:kheera,代码行数:30,代码来源:TestExecutionController.java

示例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));
        }
    }
}
 
开发者ID:quanticc,项目名称:sentry,代码行数:40,代码来源:Self.java

示例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));
}
 
开发者ID:bbakerman,项目名称:java-dataloader,代码行数:36,代码来源:DataLoaderTest.java

示例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;
    });
}
 
开发者ID:Kindrat,项目名称:cassandra-client,代码行数:43,代码来源:CassandraClientAdapter.java

示例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"));
}
 
开发者ID:salesforce,项目名称:storm-dynamic-spout,代码行数:42,代码来源:RoundRobinBufferTest.java

示例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()));
    });
}
 
开发者ID:avaire,项目名称:avaire,代码行数:14,代码来源:MessageCreate.java

示例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
    }
}
 
开发者ID:xstefank,项目名称:lra-service,代码行数:12,代码来源:Transaction.java

示例9: getTransactionRequestAsync

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<GetTransactionRequestResponseVO[]> getTransactionRequestAsync(final GetTransactionRequestRequestVO request) {
    return CompletableFuture.supplyAsync(() -> getTransactionRequest(request), getExecutorService());
}
 
开发者ID:enjin,项目名称:Enjin-Coin-Java-SDK,代码行数:5,代码来源:TransactionRequestsAsyncServiceImpl.java

示例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);
}
 
开发者ID:RBMHTechnology,项目名称:vind,代码行数:4,代码来源:CompletableSearchServer.java

示例11: personNamesAsync

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@GetMapping("/api/peopleAsync")
public CompletableFuture<Collection<String>> personNamesAsync() {
    return CompletableFuture.supplyAsync(() -> Collections.singletonList("jon"));
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:5,代码来源:PersonController.java

示例12: execute

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
public CompletableFuture<ResultSet> execute(String cql) {
    return CompletableFuture.supplyAsync(() -> template.get().query(cql));
}
 
开发者ID:Kindrat,项目名称:cassandra-client,代码行数:4,代码来源:CassandraClientAdapter.java

示例13: createIdentityAsync

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<CreateIdentityResponseVO> createIdentityAsync(final CreateIdentityRequestVO request) {
    return CompletableFuture.supplyAsync(() -> createIdentity(request), getExecutorService());
}
 
开发者ID:enjin,项目名称:Enjin-Coin-Java-SDK,代码行数:5,代码来源:IdentitiesAsyncServiceImpl.java

示例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)));
}
 
开发者ID:Kindrat,项目名称:cassandra-client,代码行数:4,代码来源:CassandraClientAdapter.java

示例15: getIdentityAsync

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<GetIdentityResponseVO[]> getIdentityAsync(final GetIdentityRequestVO request) {
    return CompletableFuture.supplyAsync(() -> getIdentity(request), getExecutorService());
}
 
开发者ID:enjin,项目名称:Enjin-Coin-Java-SDK,代码行数:5,代码来源:IdentitiesAsyncServiceImpl.java


注:本文中的java.util.concurrent.CompletableFuture.supplyAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。