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?
Asked
Active
Viewed 682 times
1

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

Schrodinger's_hat
- 57
- 6
-
Just test it to get the answer. – Braj Aug 18 '14 at 16:42
-
What do you mean class finished? Please post your code – usha Aug 18 '14 at 16:42
-
You mean if the main thread of the application stops, any of the threads fired by the `ScheduledExecutorService` will still be alive? – Luiggi Mendoza Aug 18 '14 at 16:42
-
@LuiggiMendoza yes that is essentially what I mean user3218114 I'm getting errors, my code is FAR to long to post, I think i found the error and am just trying to confirm whether I've pinpointed it or not. It's not as simple as just testing it out – Schrodinger's_hat Aug 18 '14 at 16:51
-
Create a new main method to run that adds tasks that will finish/run after the main method has returned. This is extremely easy to test. – Sotirios Delimanolis Aug 18 '14 at 17:04
-
How could the thread executor ever know that the main thread has exited? – Raedwald Aug 18 '14 at 18:38
1 Answers
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.
-
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
-