Search code examples
javaswingswingworkerexecutorservice

Multiple SwingWorkers with ExecuterService does not work properly


I am using swing and in my application i needed to run many threads in parallel like checking the internet connectivity after every 5 secs, monitoring the filesystem changes, sycing files from server.

All the time consuming tasks like above are running in SwingWorker so that my GUI should not freeze.

Same time i need to run some other time consuming tasks such as uploading file to server. for this purpose i also used swingWorker. and then i submit all these swingworker to executerService for thread pooling so that they should not effect each other.

My executer service is like this. i thought 30 threads will be enough for me.

static ExecutorService threadExecutor;
threadExecutor = Executors.newFixedThreadPool(30);

and then i submit threads in the same service.

threadExecutor.submit(monitorinternetconnectivity); //submitting swingworker obejct

Some of the threads i submit at the start and some i add runtime, when i add at runtime, it does not complete the job or stop running their job, like monitoring internet connectivity.

Is there any way to have the same functionality like swing worker, or some best way to use multiple swingworker. and we should be able to add new swingwokers at runtime to executer service


Solution

    1. SwingWorker uses it's own ThreadPool.
    2. SwingWorker should be used for a long running task after (i.e. anything that required more than a couple of milliseconds) after which a GUI update is required.
    3. No calls to update gui elements outside the EDT should be done (i.e. from the SwingWorker.done() method)

    If you generally follow the rules of accessing Swing components form inside the EDT (look here) then you shouldn't have a problem with locking. I suspect that the problem rather lies in your code but to be sure of that we should see it.