1

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?

Poliquin
  • 2,937
  • 4
  • 28
  • 32
  • please read http://stackoverflow.com/questions/6283541/java-swingworker-socket-server-does-not-get-cancelled-when-i-cancel-the-the-swing/6284186#6284186 – mKorbel Jun 08 '11 at 19:35
  • @Yakult121 How did you solved your this problem? – Xara May 20 '12 at 18:12

1 Answers1

4

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

mre
  • 43,520
  • 33
  • 120
  • 170
meverett
  • 921
  • 5
  • 6
  • Thanks for the prompt response, meverett! Let me look into this immediately. – Poliquin Jun 08 '11 at 18:26
  • Hey meverett, won't that run on the EDT? I thought that would freeze the screen when blocking IO is going on? – Poliquin Jun 08 '11 at 18:38
  • @Yakult121, `SwingWorker` also publishes on the EDT. what @meverett is suggesting is to use an `ExecutorService` instead of `SwingWorker` and once the data is ready to be published, invoke `SwingUtilties.invokeLater(...)` to make sure it's published on the EDT, which is where all Swing component updates should happen. – mre Jun 08 '11 at 18:48
  • Hi mre, thanks for the explanation. I'll look into it now. Not good at Java but trying my best! – Poliquin Jun 08 '11 at 18:53
  • @Yakult121, no worries...you're doing fine...asking all the right questions. :) – mre Jun 08 '11 at 19:01
  • Hi mre, I was thinking about the pseudocode for writing a multiclient socket server (i.e. clients connect to one predefined port - then the socket server hands off to another thread) using ExecutorService. As I'm not very sure about this, hope you can share your thoughts. Do you mean that an ExecutorService should start (execute) a SocketHandler? If so, where should the SocketServer code be residing at? Would this be the case of an ExecutorService calling a SocketServer, in turn the SocketServer call another ExecutorService (so that the socketserver can hand off the client connections to?) – Poliquin Jun 08 '11 at 19:04