I have looked all over for this answer, but can not seem to find it, so apologies if this is a dumb question. Please be gentle.
I am writing a simple MVC framework, and am getting confused on SwingWorker
and how it works with ExecutorService
.
I want to limit the number of threads which ExecutorService permits me to by using Executors.newFixedThreadPool(n)
.
I understand the importance of using SwingWorker as it has methods for performing a lengthy task (doInBackground
...etc) and allows changes to the GUI via the Event Dispatch Thread.
However, creating Executors.newFixedThreadPool(n)
limits the number of threads to n
whereas SwingWorker
seems to have a limit of 10 threads set by some kind of private internal constant MAX_WORKER_THREADS
.
What I want to know am I barking up the wrong tree trying to combine these two classes to limit the number of threads, as the implication seems to be if I submit a SwingWorker
task to an Executor
, will that one task spawn up to ten threads?
My eventual aim is to write a program which will have some intensive computations, and I do not want to make such a fundamental error from the outset, as this could prove to be a resourcing consumption problem, that is, I will have a lovely responsive GUI by proper use of the EDT, but then it will become unresponsive if each task is spawning up to 10 threads of its own!
SwingWorker
work with ExecutorService
?ExecutorService
instance which is used
to execute tasks that you submit via SwingWorker
mechanism.ExecutorService
is hidden as it is part of SwingWorker
implementation and you may not edit it.SwingWorker
implements Runnable
, you can submit it to your own ExecutorService
instance.execute()
method, then it will be scheduled to it's own ExecutorService
. Instead, you can manually submit the SwingWorker
instance to your own ExecutorService
.SwingWorker
task to an Executor, will that one task spawn up to ten threads?ExecutorService
documentation. One task will only use one thread (unless you
specifically program multithreaded task).ExecutorService
. This consumes almost no CPU time.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.