1

Say you have a ScheduledExecutorService that is initialized in the main thread of the application and we add scheduled jobs to this service. If the main thread finishes, will the ScheduledExecutorService automatically cease creating new threads?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332

1 Answers1

2

It depends on whether the underlying thread of the Executor is a daemon thread.

In the default configuration it is not the case. This means that the executor won't stop when the end of main is reached. This also means that the Executor could still create new threads.

However, if the executor uses daemon threads the application will terminate if there are no other non-daemon threads.

kellyfj
  • 6,586
  • 12
  • 45
  • 66
Jimmy T.
  • 4,033
  • 2
  • 22
  • 38
  • Also, the `ScheduledExecutorService` works with a specific set of threads. It doesn't create threads per need, like the `CachedExecutorService`. – Luiggi Mendoza Aug 18 '14 at 17:31
  • @LuiggiMendoza ScheduledThreadPoolExecutor has a corePoolSize which is "the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set". http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html#ScheduledThreadPoolExecutor(int) ScheduledThreadPoolExecutor is a subclass of ThreadPoolExecutor and passes Integer.MAX_VALUE to the super constructor. This means that it can create as many threads as it needs. – Jimmy T. Aug 18 '14 at 17:44
  • This answer is wrong. Other threads do not die just because the main thread dies, unless the main thread is the sole non-daemon thread. See http://stackoverflow.com/questions/7416018/when-does-the-main-thread-stop-in-java – Raedwald Aug 18 '14 at 18:34
  • @Raedwald I didn't say that but I added a clarification. – Jimmy T. Aug 18 '14 at 18:39