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!

有帮助吗?

解决方案

How does SwingWorker work with ExecutorService?

  • Swing maintains an internal ExecutorService instance which is used to execute tasks that you submit via SwingWorker mechanism.
  • I believe that the instantiation of the ExecutorService is hidden as it is part of SwingWorker implementation and you may not edit it.
  • But at the same time, since SwingWorker implements Runnable, you can submit it to your own ExecutorService instance.
  • If you call execute() method, then it will be scheduled to it's own ExecutorService. Instead, you can manually submit the SwingWorker instance to your own ExecutorService.

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top