5

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());
}
Ari
  • 3,460
  • 3
  • 24
  • 31
has19
  • 1,307
  • 16
  • 31

1 Answers1

3

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

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • if i do that ,only the first task submitted to the executor works ,if i submit another task it doesn't work anymore even though the first task is completed – has19 Aug 08 '16 at 16:59
  • oops your right ,i have been trying to solve this for like 10 hours ,it seems that my task never actually finish because i was calling Looper.loop at the end of run method – has19 Aug 08 '16 at 18:35
  • 2
    THat makes sense. If you call Looper.loop(), it will wait for new messages forever, thus never actually exit the task. Which means any other tasks you schedule never get run. – Gabe Sechan Aug 08 '16 at 18:36
  • yes my phone was actually get overheating as well it seems that i have been running like a 100 thread without even knowing :) ,thx – has19 Aug 08 '16 at 18:38