10

Is there an upper limit on the number of Swing Worker threads that can be run or is it like as far as the memory supports? Also is this configurable somewhere?

Sreenath Prem
  • 101
  • 1
  • 3
  • I think a confusing point with SwingWorkers is that the SwingWorker.execute() method runs the workers on a default/private thread pool, which is fixed to some low number of threads. This is likely sufficient and reasonable for small/simple apps. However, make two observations to get more control over the concurrency: 1. SwingWorkers are RunnableFutures 2. SwingWorkers do NOT have to be run by calling the SwingWorker.execute() method. So, just make your own thread pool (ExecutorService) configured to your needs, and then submit() or execute() SwingWorkers there. – Greg Mattes Aug 03 '12 at 14:54

2 Answers2

14

A SwingWorker is not a thread itself but a task that will be executed in a thread. Usually, you would use an ExecutorService to execute instances of SwingWorker; this interface also allows to set the number of threads:

 int n = 20; // Maximum number of threads
 ExecutorService threadPool = Executors.newFixedThreadPool(n);
 SwingWorker w; //don't forget to initialize
 threadPool.submit(w);

Now, if you submit more than n SwingWorker instances, they'll have to queue up and wait until a thread from the pool gets available.

mort
  • 12,988
  • 14
  • 52
  • 97
  • So you are saying theoretically I can run any number of Swing Worker tasks provided I run individual threads for each of them. – Sreenath Prem Dec 02 '11 at 13:25
  • In principle yes; of course computing power will be an issue. – mort Dec 02 '11 at 13:34
  • 3
    umm....what? why would you do this? SwingWorker has its own pool that defaults to size 10, and when you invoke `SwingWorker#execute()` it schedules the task.`Schedules this SwingWorker for execution on a worker thread. There are a number of worker threads available.`: https://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html#execute() ...doing this yourself is re-inventing the wheel. `SwingWorker` was a utility created so you wouldn't have to do this. The only reason you would do this is if the default pool size of 10 was too small, and at that point you would use a raw `Runnable` – searchengine27 Jan 27 '16 at 22:20
3
final int corePoolSize = 100;
final int maximumPoolSize = 100;
final long keepAliveTime = 100000;
final TimeUnit unit = TimeUnit.SECONDS;
final BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(maximumPoolSize);
sun.awt.AppContext.getAppContext().put(SwingWorker.class,
                 new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue));

The above code sample will allow you to have more than the default number of SwingWorkers executing. Of course it is accessing some backdoor sun.awt.AppContext class, but it is a quick workaround for those interested, and not able/willing to provide their own ExecutorService.

racc
  • 1,222
  • 10
  • 13