Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of active threads keeps increasing

I am using executorService to excecute only one task at a time using this code

executorService=Executors.newSingleThreadExecutor();

And I am using Thread.activeCount() to get the number of active threads, but whenever I submit a runnable task to the executorService the number of active threads is incremented by one. How is that possible?

I thought newSingleThreadExecutor() allows executing only one task at a time. Why does the number of threads keep increasing? Shouldn't the number of threads only increase by one and not more?

Note that I am also using future to cancel execution of all runnables before even submitting a new task and it works fine; all runnables are interrupted. However, the number of active threads keeps increasing.

Edit: This is the code that gets called whenever I press on a button (Worker is just a class that implements runnable):

private void handle() {
    executorService=Executors.newSingleThreadExecutor();
    Worker worker=new Worker();
    future=executorService.submit(new Worker());
}
like image 395
has19 Avatar asked Oct 29 '22 22:10

has19


1 Answers

Each time you call it it cretes a new Executor. Each single threaded executor has its own thread. If you want to do multiple jobs on that executor you call newSingleThreadedExecutor once and submit all the jobs to that executor. You do not call newSingleThreadedExecutor multiple times

like image 165
Gabe Sechan Avatar answered Nov 15 '22 07:11

Gabe Sechan