Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should ExecutorService be static and global

I want to use the same thread pool throughout my application. To this end, I can make ExecutorService static and global so that I can invoke ThreadUtil.executorService to get ExecutorService when I need it.

public class ThreadUtil {
    public static final ExecutorService executorService = Executors.newCachedThreadPool();
}

Is it OK to instance multiple thread pools like this?

In addition, my application is a TCP server. If I don't know how big the pool should be, is it ok to simply use newCachedThreadPool?

like image 524
bylijinnan Avatar asked Apr 20 '15 00:04

bylijinnan


1 Answers

When an instance with the same properties is to be used anywhere in your program, it is logical to declare it static and final instead of re-creating the instance each time but I would personally opt for a Singleton pattern instead of directly giving public access to the instance.

As for your second query, I don't see any problem with it. The first sentence of the documentation for newCachedThreadPool says

Creates a thread pool that creates new threads as needed

since you don't know how many threads will be created, this is the most logical choice.

Note that newCachedThreadPool will re-use old threads when they are available to increase performance.

like image 71
Jean-François Savard Avatar answered Nov 02 '22 02:11

Jean-François Savard