How does SwingWorker
work with ExecutorService
?
- Swing maintains an internal
ExecutorService
instance which is used to execute tasks that you submit viaSwingWorker
mechanism. - I believe that the instantiation of the
ExecutorService
is hidden as it is part ofSwingWorker
implementation and you may not edit it. - But at the same time, since
SwingWorker
implementsRunnable
, you can submit it to your ownExecutorService
instance. - If you call
execute()
method, then it will be scheduled to it's ownExecutorService
. Instead, you can manually submit theSwingWorker
instance to your ownExecutorService
.
If I submit a SwingWorker
task to an Executor, will that one task spawn up to ten threads?
- No. To understand this, you should go through
ExecutorService
documentation. One task will only use one thread (unless you specifically program multithreaded task). - Other threads are kept in idle by
ExecutorService
. This consumes almost no CPU time. - If 10 GUI events occur simultaneously, each will be assigned to each of the available thread. If the thread is not required, it will not be running.
- If number of tasks is more than number of threads available, they will be scheduled in a queue by the
ExecutorService
itself.
Hope this clears the doubts. Usually it is a good idea to use default implementation (it works very well), but you easily can limit number of threads if you want. Also, it will not replace Swing's ExecutorService
. Since it is already there, it's best to use it instead of creating another.
Good Luck.