是否可以为Java 8 并行流指定自定义线程池?我找不到任何地方.
想象一下,我有一个服务器应用程序,我想使用并行流.但是应用程序很大且是多线程的,因此我想将它划分为区分.我不想在另一个模块的应用程序块任务的一个模块中执行缓慢的任务.
如果我不能为不同的模块使用不同的线程池,这意味着我无法在大多数现实情况下安全地使用并行流.
请尝试以下示例.在单独的线程中执行一些CPU密集型任务.这些任务利用并行流.第一个任务被破坏,因此每个步骤需要1秒(通过线程休眠模拟).问题是其他线程卡住并等待损坏的任务完成.这是一个人为的例子,但想象一下servlet应用程序和有人向共享fork连接池提交长时间运行的任务.
public class ParallelTest {
public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newCachedThreadPool();
es.execute(() -> runTask(1000)); //incorrect task
es.execute(() -> runTask(0));
es.execute(() -> runTask(0));
es.execute(() -> runTask(0));
es.execute(() -> runTask(0));
es.execute(() -> runTask(0));
es.shutdown();
es.awaitTermination(60, TimeUnit.SECONDS);
}
private static void runTask(int delay) {
range(1, 1_000_000).parallel().filter(ParallelTest::isPrime).peek(i -> Utils.sleep(delay)).max()
.ifPresent(max -> System.out.println(Thread.currentThread() + " " + max));
}
public static boolean isPrime(long n) {
return n > 1 && rangeClosed(2, (long) sqrt(n)).noneMatch(divisor …Run Code Online (Sandbox Code Playgroud) newCachedThreadPool() 与 newFixedThreadPool()
我什么时候应该使用其中一种?哪种策略在资源利用方面更好?
java concurrency multithreading executorservice threadpoolexecutor
我正在开发一个项目,我需要确保每个线程都在特定范围内工作.例如:
NO_OF_THREADS: 2
NO_OF_TASKS: 10
Run Code Online (Sandbox Code Playgroud)
如果number of threads is 2和number of tasks is 10则每个线程将被执行10 tasks.这意味着2个线程将会这样做20 tasks.
在实际场景中,这些数字(任务数和线程数)将非常高,因为它们都可以在我的代码中配置.
在上面的例子中,first thread应该使用id之间1 and 10和之间second thread应该使用id 11 and 20等等,如果有更多的线程.之后,每个线程将建立数据库连接,然后插入数据库.
所以我的下面的代码工作正常.
public static void main(String[] args) {
final int noOfThreads = 2;
final int noOfTasks = 10;
//create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
// queue some tasks
for (int i = 0, int nextId = 1; …Run Code Online (Sandbox Code Playgroud) 我有一个异步执行的查询输入流。我想确保当我使用时Completablefuture::join,这些要求的结果是按照输入查询流的顺序收集的。
这是我的代码的样子:
queries.stream()
.map(query -> CompletableFuture.supplyAsync(() -> {
try {
return SQLQueryEngine.execute(query);
} catch (InternalErrorException e) {
throw new RuntimeException(e);
}
}))
.map(CompletableFuture::join)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
SQLQueryEngine.execute(查询); 返回一个List<Results>so 输出是List<List<Result>。我想展平并将所有结果合并到一个列表中。如果我在收集之前使用 .flatMap(List::stream) 来扁平化,它会保持排序吗?