Reputation: 1189
I have a service method, which need to call three methods in parallel, like below to make the ServiceMethod()
run faster.
public void ServiceMethod()
{
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
});
executorService.shutdown();
}
Also I want to mention that the ServiceMethod()
maybe called by 1000 clients at the same time, below is my puzzles.
If the ServiceMethod()
is called 1000 times, then we would create 1000 different Threadpool and each of them will contain 10 threads, so there would be 10,000 threads? And there is no chance that the threads would be reused?
How about if I moved the
ExecutorService executorService = Executors.newFixedThreadPool(10);
from the method scope to the class level with
static ExecutorService executorService = Executors.newFixedThreadPool(10);
? with static variable? Then all of the 1000 clients share the 10 threads and only in such case, the threads would be reused?
Upvotes: 0
Views: 274
Reputation: 6197
You're right. Creating and destroying ExecutorService
's for every request is very wasteful and not scalable. Even given the fact that the threads are destroyed when you shutdown and release an executor (so, you probably won't have 10,000 threads at the same time), it's still too expensive to create and start new threads when a request arrives.
The common approach is to have a single shared executor with a decent number of threads that is used by all requests to submit tasks. Though, the executor doesn't have to be static. If you have a single object that handles all the requests, just make it a simple class field.
Upvotes: 1