views:

127

answers:

1

I'm trying to execute a SwingWorker (SubWorker) from another SwingWorker (MainWorker), and then I want the MainWorker to wait for the SubWorker to complete. In the mean time, the MainWorker should update itself according to property changes of the SubWorker.

public class MainWorker extends SwingWorker<Void,Void>
{
    public Void doInBackground()
    {
        SubWorker sw = new SubWorker();
        sw.execute();
        try {
            network.get(); // wait for completion
        } catch (Exception ex) {
        }
        return null;
    }
}

The problem is that the SubWorker's doInBackground method is not called until the MainWorker has finished, while the MainWorker is waiting for the SubWorker to finish.

How can I let the SubWorker run parallel to the MainWorker's activities?

+3  A: 

If you have only one sub-worker, I'm not sure what is the point - why can't you just execute the task in the SW body?

If you have multiple parallel sub-tasks, and you want to group them and report on their progress, you don't really need separate SwingWorkers - just start threads or use an executor to schedule the tasks. If you want to publish interim results, pass a blocking queue to the tasks, where they would push the updates.

The main (or rather the only) SwingWorker would take items from that queue and update the GUI using the publish()/process() methods. When a subtask finishes work, it can push special token in the queue (or null). That's how you can keep track of the outstanding subtasks and decide when to terminate the loop.

Alternatively, if you have a bunch of self-contained tasks you can use CompletionService and update the status in similar way from the SW.

ddimitrov
Thanks, using an Executor solves the problem.
RemiX