If you delve into the SwingWorker
code you'll see the following constant defined:
/**
* number of worker threads.
*/
private static final int MAX_WORKER_THREADS = 10;
Hence, the number of background threads can never exceed this value irrespective of the number of SwingWorker
's you actually create.
One way to vary the background threading model would be to plug your own ExecutorService
into the AppContext
associated with the SwingWorker
class. However, this is slightly dodgy given that AppContext
belongs to sun.awt
and hence is not part of the official JDK API.
// Create single thread executor to force all background tasks to run on the same thread.
ExecutorService execService = Executors.newSingleThreadExecutor();
// Retrieve the AppContext. *CAUTION*: This is part of the sun.awt package.
AppContext ctxt = AppContext.getAppContext();
// Verify that nothing is already associated with SwingWorker.class within the context.
Object obj = ctxt.get(SwingWorker.class);
if (obj != null) {
throw new IllegalStateException("Object already associated with SwingWorker: " + obj);
}
// Install ExecutorService. Will be retrieved by the SwingWorker when execute() is called.
ctxt.put(SwingWorker.class, ctxt);