Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't ScheduledExecutorService spawn threads as needed?

Tags:

java

In my application I use ScheduledExecutorService, but only one thread is spawned to handle the scheduled tasks. Is this because ScheduledExecutorService does not spawn threads to handle the pending tasks?

Here is a code snippet that will output only "run() 1" instead of the expected "run() 1" followed by "run() 2" ... "run() 10."

public class App {

    public static void main(String[] args) {
        int N = 10;
        Runnable runner = new Runnable() {

            public void run() {
                foo();
            }
        };
        for (int i = 0; i < N; i++) {
            executor.schedule(runner, i, TimeUnit.MILLISECONDS);
        }
    }

    private static void foo() {
        System.out.println("run() " + (++n));
        synchronized (executor) {
            try {
                executor.wait();
            } catch (InterruptedException ex) {
                Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        System.out.println("finished()");
    }
    private static Logger logger = Logger.getLogger(App.class.getName());
    private static int n = 0;
    private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
}
like image 432
Michael Avatar asked Jul 26 '12 21:07

Michael


People also ask

How thread pool Executor works?

ThreadPoolExecutor is an ExecutorService to execute each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. It also provides various utility methods to check current threads statistics and control them.

How to wait for Executor to finish?

When using an Executor, we can shut it down by calling the shutdown() or shutdownNow() methods. Although, it won't wait until all threads stop executing. Waiting for existing threads to complete their execution can be achieved by using the awaitTermination() method.

How ExecutorService works?

The Java ExecutorService's execute() method takes in a runnable object and performs its task asynchronously. After making the call to execute method, we call the shutdown method, which blocks any other task to queue up in the executorService. The submit() method takes in a runnable object and returns a Future object.

What is ScheduledExecutorService in Java?

public interface ScheduledExecutorService extends ExecutorService. An ExecutorService that can schedule commands to run after a given delay, or to execute periodically. The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution.


2 Answers

There is only one thread because you create the thread pool with Executors.newScheduledThreadPool(1), which means that the thread pool contains only 1 thread. If you want 10 threads, pass 10 as argument. Note that the documentation of ScheduledThreadPoolExecutor, which is what this method returns, explicitly says that the thread pool has a fixed size.

like image 173
JB Nizet Avatar answered Nov 03 '22 01:11

JB Nizet


From the javadoc for ScheduledThreadPoolExecutor:

While this class inherits from ThreadPoolExecutor, a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. Additionally, it is almost never a good idea to set corePoolSize to zero or use allowCoreThreadTimeOut because this may leave the pool without threads to handle tasks once they become eligible to run.

In other words, maximumPoolSize == corePoolSize. You set corePoolSize to 1, so that's all it will spawn.

like image 35
Jim Garrison Avatar answered Nov 03 '22 00:11

Jim Garrison