I am trying to do a simple calculation (it calls Math.random()10,000,000 times). Amazingly launching it in a simple way, it works much faster than using the ExecutorService.
I read another topic at the amazing ExecutorService break-even point - thumb rules? and tried to execute the answer by executing Callableusing batches, but performance is still poor
How to improve performance based on my current code?
import java.util.*;
import java.util.concurrent.*;
public class MainTest {
public static void main(String[]args) throws Exception {
new MainTest().start();;
}
final List<Worker> workermulti = new ArrayList<Worker>();
final List<Worker> workersingle = new ArrayList<Worker>();
final int count=10000000;
public void start() throws Exception {
int n=2;
workersingle.add(new Worker(1));
for (int i=0;i<n;i++) {
workermulti.add(new Worker(n));
}
ExecutorService serviceSingle = Executors.newSingleThreadExecutor();
ExecutorService serviceMulti = Executors.newFixedThreadPool(n);
long s,e;
int tests=10;
List<Long> simple = new ArrayList<Long>();
List<Long> single = new ArrayList<Long>();
List<Long> multi = new ArrayList<Long>();
for (int i=0;i<tests;i++) {
s = System.currentTimeMillis();
simple();
e = System.currentTimeMillis();
simple.add(e-s);
s = System.currentTimeMillis();
serviceSingle.invokeAll(workersingle);
e = System.currentTimeMillis();
single.add(e-s);
s = System.currentTimeMillis();
serviceMulti.invokeAll(workermulti);
e = System.currentTimeMillis();
multi.add(e-s);
}
long avgSimple=sum(simple)/tests;
long avgSingle=sum(single)/tests;
long avgMulti=sum(multi)/tests;
System.out.println("Average simple: "+avgSimple+" ms");
System.out.println("Average single thread: "+avgSingle+" ms");
System.out.println("Average multi thread: "+avgMulti+" ms");
serviceSingle.shutdown();
serviceMulti.shutdown();
}
long sum(List<Long> list) {
long sum=0;
for (long l : list) {
sum+=l;
}
return sum;
}
private void simple() {
for (int i=0;i<count;i++){
Math.random();
}
}
class Worker implements Callable<Void> {
int n;
public Worker(int n) {
this.n=n;
}
@Override
public Void call() throws Exception {
for (int i=0;i<(count/n);i++) {
Math.random();
}
return null;
}
}
}
Output for this code
Average simple: 920 ms
Average single thread: 1034 ms
Average multi thread: 1393 ms
EDIT: Performance suffers because Math.random () is a synchronized method. After changing Math.random () with a new Random object for each thread, performance is improved
( Math.random() Random )
Average simple: 928 ms
Average single thread: 1046 ms
Average multi thread: 642 ms