Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run X tasks on Y threads in Java?

I want to meassure an average time of executing a task on 5 threads doing 100 tasks.

For time meassuring purposes I use nanoTime()

The task is calling one specific method, let's call it foo(); I don't create any additional classes.

In my code I create a task:

Runnable thExecute = new Runnable(){
  @Override
  public void run(){
    foo();
  }
};

And then I create a thread:

Thread th = new Thread(thExecute);
long start = System.nanoTime();
th.run();
long stop = System.nanoTime();

This would be great if I had the same number of tasks as threads. I tried to create arrays of threads and tasks:

Runnable[] thExecutes = new Runnable[100];
Thread[] ths = new Thread[5];

But now I don't know what to do next. I know they should be queued somehow and probably I should use Executor class. I use Java 6.

Edit: At first I didn't mean what I wrote. Now I know I want average time + highest time.

like image 396
Kamil Avatar asked Mar 14 '23 13:03

Kamil


1 Answers

First thing to note: you should not expect precise results, if you measure performance by yourself. There are tools that do it for you, providing much more reliable results.

If you want to do it by yourself, use ExecutorService:

ExecutorService service = Executors.newFixedThreadPool(5);
long startTs = System.nanoTime();

List<Future> futures = new ArrayList<>();
for (Runnable r : runnables) {
    futures.add(service.submit(r));
}
for (Future f : futures) { 
    f.get(); 
}

long durationNs = System.nanoTime() - startTs;

And again: since you are measuring nanoseconds, I strongly encourage you to avoid manual measurements, because there are many factors that will spoil the results: no warmup, setup expenses, etc.

Update: to measure execution time of every task, you can submit Callable<Long> instead of Runnable

public long call() {
    long startTs = System.nanoTime();
    // do the task
    return System.nanoTime() - startTs;
}

Now Future will return the execution time, you can print it or gather in a list:

for (Future<Long> f : futures) {
    long spentTime = f.get();
}
like image 80
AdamSkywalker Avatar answered Mar 16 '23 20:03

AdamSkywalker