I have class A, and there will be multiple instance of the class at run time.
Does each instance create 5 threads with the below code?
public class A {
private void someMethod1(){
getPool();
}
private static ExecutorService getPool() {
return (ExecutorService) new ThreadPoolExecutor(0, 5,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
}
Requirement:
If there are 9 instances of class A, there will be 9*5=45 threads will be created? I am looking for a solution where the number of threads for example 50 cache able thread should be created only once and then any instance of that class should be reuse this pool of threads
i think what you are looking for is a singleton, create a new static class with a getter to get executor service,and call it anywhere you like:
public class MyExecutors {
private static ExecutorService ex;
public static synchronized ExecutorService getExecutor(){
if(ex == null){
ex = new ThreadPoolExecutor(0, 50, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
}
return ex;
}
}
now just use MyExecutors.getExecutor()
in all your instances. this will ensure the same executor instance for each class