开发者

how do FutureTasks and CachedThreadPool work

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 co开发者_如何学Pythonnsole 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜