Java并发: How to select and configure Executors

标签 java concurrency

Java 并发 API 为您提供了用于构建的 ExecutorExecutorService 接口(interface),并附带了多个具体实现(ThreadPoolExecutor ScheduledThreadPoolExecutor)。

我对 Java 并发性完全陌生,并且很难找到几个非常相似的相关问题的答案。我决定将它们捆绑在一起,而不是把所有这些小问题搞乱,因为可能有一种方法可以一次性回答所有这些问题(可能是因为我在这里没有看到全貌):

  • 实现自己的 Executor/ExecutorService 是常见做法吗?在什么情况下你会这样做而不是使用我上面提到的两种具体方法?在什么情况下,这两种结核比“本土”的结核更可取?
  • 我不明白所有并发集合如何与Executor相关。例如,ThreadPoolExecutor 是否在底层使用 ConcurrentLinkedQueue 来对提交的任务进行排队?或者您(API 开发人员)是否应该在并行 run() 方法中选择和使用,例如,ConcurrentLinkedQueue?基本上,并发集合是由执行器内部使用的,还是使用它们来帮助编写非阻塞算法?
  • 您可以配置 Executor 在后台使用哪些并发集合(用于存储提交的任务),这是常见的做法吗?

提前致谢!

最佳答案

Is it common practice to implement your own Executor/ExecutorService?

没有。我从来没有这样做过,而且我已经使用并发包有一段时间了。这些类的复杂性以及使它们“错误”所带来的性能影响意味着您在进行这样的项目之前应该真正仔细考虑一下。

我唯一一次觉得需要实现自己的执行器服务是当我想实现“自运行”执行器服务时。直到一个 friend 告诉我有一个way to do it with a RejectedExecutionHandler .

我想要调整 ThreadPoolExecutor 行为的唯一原因是让它启动所有线程,直到达到最大线程数,然后然后坚持下去将作业放入队列中。默认情况下,ThreadPoolExecutor 启动最小线程,然后在启动另一个线程之前填充队列。不是我所期望或想要的。但随后我只需从 JDK 复制代码并对其进行更改,而不是从头开始实现。

I don't understand how all of the concurrent collections relate to Executors. For instance, does ThreadPoolExecutor use, say, ConcurrentLinkedQueue under the hood to queue up submitted tasks?

如果您使用的是 Executors 辅助方法之一,则不必担心这一点。如果您自己实例化 ThreadPoolExecutor,则需要提供要使用的 BlockingQueue。

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
           0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}

对比:

 ExecutorService threadPool = 
     new ThreadPoolExecutor(minThreads, maxThreads, 0L, TimeUnit.MILLISECONDS,
            new SynchronousQueue<Runnable>());

Can you configure which concurrent collections an Executor uses under the hood (to store submitted tasks), and is this common practice?

查看最后一个答案。

关于Java并发: How to select and configure Executors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11267076/

相关文章:

java - OOP循环引用

java - 比较 Java 7 中的 Object 和 int

java - 通过 awselb 使用 ssl 时的 neo4j java 驱动程序问题

java - ExecutorService 的 future 任务并未真正取消

java - 并发 - 数据库访问

java - 在哪里放置 hibernate.dialect.storage_engine 属性

java - 时间戳sql查询

c# - MSDN 上 SimplePriorityQueue 示例中的严重错误

java - Futures、TimeoutException 和带有finally block 的Callables

java - 图像渲染在框架之外?