Weize Sun
Weize Sun

Reputation: 155

Will ExecutorService block the method it lies in?

I am a newbie in Java and I know my question may be silly... I found that my main method is prevented from returning by the ExecutorService if I do not invoke ExecutorService.shutdown():

class Test{
    public static void main(String[] args){
        ExecutorService exec = new Executors.newCachedThreadPool();
        exec.execute(new Runnable(){
            public void run(){
                System.out.println("I am running!");
            }
        });
    }
}

The code above will not return in the main thread. I wonder why the ExecutorService keeps blocking the main method, does it aim at forcing the programmer to invoke shutdown()?

Upvotes: 1

Views: 708

Answers (2)

rmlan
rmlan

Reputation: 4657

I think you are misunderstanding what is happening. It is not that it is blocking the main method, but the JVM is still running because by creating an executor and submitting a task to it, you have started another thread in the JVM.

This executor does not know how many tasks you intend to submit to it, so it will keep its thread(s) running until you explicitly tell it to shut down.

Upvotes: 6

Roee Gavirel
Roee Gavirel

Reputation: 19443

It is not blocking, it is just that in Java as long is there are non-daemon threads the application is not closing:

class Test{
    public static void main(String[] args){
        ExecutorService exec = new Executors.newCachedThreadPool();
        exec.execute(new Runnable(){
            System.out.println("I am running!");
        });
        System.out.println("I am Main!"); //This will run...
    }
}

If you want to close the application you will have to shutdown the executorService.

Upvotes: 9

Related Questions