Search code examples
javaswingswingworkersecondaryloop

SwingWorker for Both Output & Work, or 1 Each?


Currently I always create a SwingWorker to do my actual work, and another to process the output via a PipedReader.

I'd love to combine the two, but I just don't see an easy way to do it, in my situation.

Given that I:

  1. Have a pre-made object that does work (converter, in this case)
  2. Want to routinely display updates on converter's progress to the GUI
  3. Receive an object when converter finishes its task and returns.

Is there a way to do this without two SwingWorkers?

Edit: Note that making converter extend SwingWorker is not an option.

Edit 2: In response to comment below. This is part of a larger GUI application, processing large chunks of data (in the form of txt) and informing the user what is wrong, or what has been decided.

Example Code (purely illustrative, not used):

//SwingWorker 1
@Override
protected Void doInBackground() {

   outputWorker.useInStream(new PipedReader(outStream));
   outputWorker.execute();
   converter.usePipedWriter(outStream);
   Output object2=converter.Convert(object1);

}

//SwingWorker 2
@Override
protected Void doInBackground() {

   while(inStream.hasNext()) {
      publish(inStream.next());
   }
}

Solution

  • If you are using JDK7, you might consider using SecondaryLoop instead of chaining together multiple SwingWorker instances.

    SecondaryLoop essentially allows you to wait for a background thread (or series of threads) to complete without blocking the EDT, similar to SwingWorker. It is may not be suitable as a replacement for SwingWorker in every case, however based on the description of your problem it sounds like this is something you might be able to use.

    For more discussion on this topic, please take a look related question, "SecondaryLoop instead of SwingWorker? "