Search code examples
javaswingswingworker

Java SwingWorker - using publish/process to update a TextArea in EDT?


I had just coded a Swing program that starts up a SwingWorker (which runs a Socket Server). I have a JTextArea on the Swing GUI which gets updated with the data received by the Socket Server, using a JTextArea.append(String).

Is it the correct/threadsafe way to update a JTextArea on the Swing GUI? What about using publish/process?


Solution

  • SwingWorker is usually used for one time long running processes (anything that will take more than a few milliseconds to complete). If you have persistent connection, it would be more appropriate to use a dedicated ExecutorService which will run the process, then when you want to update a swing component call

    SwingUtilities.invokeLater(new Runnable() { 
        public void run() {
            .. update here
        }
    }
    

    The reason for this is SwingWorkers use a fixed thread pool size, so if you have a process that never completes than it limits the number threads other SwingWorkers can use concurrently