Benedikt Bünz
Benedikt Bünz

Reputation: 646

How do I reuse Threads with different ExecutorService objects?

Is it possible to have one thread pool for my whole program so that the threads are reused, or do I need to make the ExecutorService global/ pass it to all objects using it.

To be more precise I have multiple tasks that run in my program but they do not run extremely often.

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

I believe that it would be unnecessary to have a full thread running all the time for every single task but it might also be costly to restart the thread every single time when a task is executed.

Is there a better alternative to making the Thread pool global?

Upvotes: 3

Views: 1752

Answers (2)

Benedikt Bünz
Benedikt Bünz

Reputation: 646

With Java 8 there is a new solution. The fork join global thread pool: http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html#commonPool--

Upvotes: 1

Gray
Gray

Reputation: 116858

How do I reuse Threads with different ExecutorService objects?

It is not possible to re-use threads across different ExecutorService thread-pools. You can certainly submit vastly different types of Runnable classes to a common thread-pool however.

Is there a better alternative to making the Thread pool global?

I don't see a problem with a "global" thread-pool in your application. Someone needs to know when to call shutdown() on it of course but that's the only problem I see with it. If you have a lot of disparate classes which are submitting tasks, they all could access this set (or 1) of common background threads.

You may find however that different tasks may want to use a cached thread pool while others need a fixed sized pool so that multiple pools are still necessary.

I believe that it would be unnecessary to have a full thread running all the time for every single task but it might also be costly to restart the thread every single time when a task is executed.

In general, unless you are forking tons and tons of threads, the relative cost of starting one up every so often is relatively small. Unless you have evidence from a profiler or some other source, this may be premature optimization.

Upvotes: 3

Related Questions