Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: ExecutorService less efficient than manual Thread executions?

I've got a multi-threaded application. When using Thread.start() to manually start threads every concurrent thread uses exactly 25% CPU (or exactly one core - this is on a quad core machine). So if I run two threads CPU usage is exactly 50%.

When using ExecutorService to run threads however, there seems to be one "ghost" thread consuming CPU resources! One Thread uses 50% instead of 25%, two thread use 75%, etc.

Could this be some kind of windows task manager artefact?

Excutor service code is

ExecutorService executor = Executors.newFixedThreadPool(threadAmount);

for (int i = 1; i < 50; i++) {
    Runnable worker = new ActualThread(i);
    executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {

}
System.out.println("Finished all threads");

and Thread.start() code is:

ActualThread one= new ActualThread(2,3);
ActualThread two= new ActualThread(3,4);
...

Thread threadOne = new Thread(one);
Thread threadTtwo = new Thread(two);
...

threadOne.start();
threadTwo.start();
...
like image 679
Oliver Avatar asked Mar 08 '11 02:03

Oliver


1 Answers

Here's your problem:

while (!executor.isTerminated()) {

}

Your "main" method is spinning the CPU doing nothing. Use invokeAll() instead, and your thread will block without a busy wait.

final ExecutorService executor = Executors.newFixedThreadPool(threadAmount);
final List<Callable<Object>> tasks = new ArrayList<Callable<Object>>();

for (int i = 1; i < 50; i++) {
    tasks.add(Executors.callable(new ActualThread(i)));
}
executor.invokeAll(tasks);
executor.shutdown();  // not really necessary if the executor goes out of scope.
System.out.println("Finished all threads");

Since invokeAll() wants a collection of Callable, note the use of the helper method Executors.callable(). You can actually use this to get a collection of Futures for the tasks as well, which is useful if the tasks are actually producing something you want as output.

like image 105
andersoj Avatar answered Sep 17 '22 22:09

andersoj