Search code examples
javamultithreadingperformancethreadpoolforkjoinpool

Why does ForkJoinPool.commonPool().execute(runnable) take more time to run the thread


I am using ForkJoinPool.commonPool().execute(runnable) as a handy way to spawn a thread in many places across my application. But at a particular invocation of that it is taking more time (more than 10 seconds) to invoke the code in the runnable in a thread. What could be the reason for that? How to avoid that?

EDIT: As per @ben 's answer, avoiding long running process in thread pool seems to the solution. Creating new thread manually solved my problem instead of using common ForkJoinPool.


Solution

  • So after some quick testing I found the issue. Look at the following example code:

    List<Runnable> runnables = new ArrayList<Runnable>();
    for (int i = 0; i < 20; ++i)
    {
        runnables.add(() -> {
            System.out.println("Runnable start");
            try
            {
                Thread.sleep(10000);
            }
            catch (InterruptedException e)
            {
    
            }
            System.out.println("Runnable end");
        });
    }
    
    for (Runnable run : runnables)
    {
        //ForkJoinPool.commonPool().execute(run);
        //new Thread(run).start();
    }
    

    Comment in one of the two lines. We create a number of runnables that send a message, sit idle for 10s and send a message again. Quite simple.

    When using Threads for each of those all Runnables send Runnable start 10s pass, all runnables send Runnable end.

    When using the commonPool() just a number of them sends Runnable start 10s pass, they send Runnable end and another bunch of them sends Runnable start until they are all finished.

    This is simply because the number of cores on your system determines how many threads the threadpool will hold. When all of them are filled new tasks are not executed until one thread is freed up.

    So moral of the story: Only use a threadpool when you know the way it works internally and that is what you want it to do.