Hi Martin,
The problem with Schedulers.shutdown()
is that it completely shuts down RxJava, making it unusable for the remainder of the program’s execution…
Since you want to shutdown your own executor, you can indeed do so by implementing the ShutdownHook
to simply call executor.shutdownNow()
, that’s a possibility. However, don’t stop RxJava if your application will continue to run.
Side Note
While testing, I also noticed that if you don’t call Schedulers.shutdown()
, after a few seconds the following exception is dumped in the console:
Exception in thread "RxScheduledExecutorPool-3" java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:62)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.util.concurrent.RejectedExecutionException: Task rx.schedulers.ExecutorScheduler$ExecutorSchedulerWorker@2402d0a6 rejected from java.util.concurrent.ThreadPoolExecutor@203d50fe[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 31]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at rx.schedulers.ExecutorScheduler$ExecutorSchedulerWorker.schedule(ExecutorScheduler.java:78)
at rx.schedulers.ExecutorScheduler$ExecutorSchedulerWorker$2.call(ExecutorScheduler.java:136)
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
... 7 more
It seems that wrapping an ExecutorService
that isn’t a ScheduledExecutorService
into a Scheduler
will cause this… If your executor wasn’t a ScheduledExecutorService
, I would use one instead (eg. Executors.newScheduledThreadPool(10, Executors.privilegedThreadFactory())
for your example).