Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java GUI and Multiple Instances of the SwingWorker Class

I'm making a GUI using Java (who isn't?). I know the Swing Worker class enables computation in the background to prevent the GUI from hanging, but I was wondering if there could be too much of a good thing here...

For instance, if there were too many instances of those background threads running, would it impact the performance of the program depending on the computer? A simple, but important question. I would greatly appreciate any input. Thanks for your time.

like image 846
RCC Avatar asked Dec 30 '22 06:12

RCC


2 Answers

Yes, the more processing you do, naturally, it will affect the performance of the computer. After all, processing resources is a limited resource.

That said, many modern computers have multiple cores, which means that a single-threaded application will probably not be able to take full advantage of the processor resources.

In general, having a few threads running is not going to be a big problem. However, once there are hundreds or thousands of threads, performance can degrade, as the time it takes to do a context switch between threads can start to take up a larger fraction of the processing resources that are available.

like image 99
coobird Avatar answered Jan 11 '23 20:01

coobird


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);
like image 27
Adamski Avatar answered Jan 11 '23 19:01

Adamski