Question

I currently have code that does the following:

private final static ExecutorService pool = Executors.newCachedThreadPool();
public void foo(){
    FutureTask<MyObject> first_task = createFutureTask();
    FutureTask<MyObject> second_task = createFutureTask();
    ...

    pool.execute(first_task);
    pool.execute(second_task);
    ....
    first_task.get();
    second_task.get();
    ...
    System.out.println(time taken);
}

The problem I'm having is that I get each of the future task to print out the time they take when doing computation, so for example on the console I will see

first_task : 20000ms
second_task : 18000ms
...

but the total time (System.out.println(time taken)) is much larger then the longest time taken by any future task, so in line with this example the method do would take around 1 minute (compared to the 20s of first_task).

I was under the impression that these future tasks run in parallel but from the timings it seems as though they are being run one after the other. Am I using this API correctly?

Was it helpful?

Solution

You're using the API correctly, but keep in mind that each task runs in a separate thread, not a separate process (and thus not necessarily in parallel).

Each thread would have to run on a separate CPU core to actually execute at the same time. Whether or not this is possible depends on your machine, its current load, and how the JVM and OS are able to schedule the threads across cores.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top