The Java Concurrency API gives you Executor and ExecutorService interfaces to build from, and ships with several concrete implementations (ThreadPoolExecutor and ScheduledThreadPoolExecutor).
I’m completely new to Java Concurrency, and am having difficulty finding answers to several very-similarly-related questions. Rather than cluttering SO with all these tiny questions I decided to bundle them together, because there’s probably a way to answer them all in one fell swoop (probably because I’m not seeing the whole picture here):
- Is it common practice to implement your own
Executor/ExecutorService? In what cases would you do this instead of using the two concretions I mention above? In what cases are the two concretions preferable over something “homegrown”? - I don’t understand how all of the concurrent collections relate to
Executors. For instance, doesThreadPoolExecutoruse, say,ConcurrentLinkedQueueunder the hood to queue up submitted tasks? Or are you (the API developer) supposed to select and use, say,ConcurrentLinkedQueueinside your parallelizedrun()method? Basicaly, are the concurrent collections there to be used internally by theExecutors, or do you use them to help write non-blocking algorithms? - Can you configure which concurrent collections an
Executoruses under the hood (to store submitted tasks), and is this common practice?
Thanks in advance!
No. I’ve never had to do this and I’ve been using the concurrency package for some time. The complexity of these classes and the performance implications around getting them “wrong” mean that you should really think carefully about it before undertaking such a project.
The only time that I felt the need to implement my own executor service was when I wanted to implement a “self-run” executor service. That was until a friend showed me that there was a way to do it with a
RejectedExecutionHandler.The only reason why I’d wanted to tweak the behavior of the
ThreadPoolExecutorwas to have it start all of the threads up to the max-threads and then stick the jobs into the queue. By default theThreadPoolExecutorstarts min-threads and then fills the queue before starting another thread. Not what I expect or want. But then I’d just be copying the code from the JDK and changing it — not implementing it from scratch.If you are using one of the
Executorshelper methods then you don’t have to worry about this. If you are instantiatingThreadPoolExecutoryourself then you provide theBlockingQueueto use.Versus:
See the last answer.