开发者

What threads are allowed to call SwingWorker#publish?

Standard scenario: User presses button and starts big task. EventThread creates SwingWorker to execute the task and get's on with life.

Now, since the big task is highly parallelizable, the first thing the SwingWorker thread does is to create a bunch of worker threads and farms the work out.

My question: Are the worker threads allowed to call SwingWorker#publish() to trigger a GUI update or is only the SwingWorker thread allowed to do so?

Thanks, Carsten

[Edit] Some pseudo code to make my use-case a bit clearer. The quesiton is basically: Is the code below OK? And what if I leave out waitForAllWorkerT开发者_如何学运维hreadsToFinish();?

public class MySwingWorker extends SwingWorker {

  class MyWorkerThread extends Runnable {
    void run() {
      while(!exitCondition) {
        doSomeWork();
        publish(progressUpdate);
        reEvaluateExitCondition();
      }
    }
  }

  public Void doInBackground() {
    createAndStartBunchOfMyWorkerThreads();
    waitForAllWorkerThreadsToFinish();
  }

  void process(List<V> chunks) {
    updateGuiWithProgress(chunks);
  }
}


In general, no; publish() is intended to run on the background thread, which must itself synchronize all the results coming from the subsidiary workers. Fortunately, you have considerable latitude in designing how the background thread does this. For instance, this example uses CountDownLatch.

Addendum: waitForAllWorkerThreadsToFinish() looks like a good use case for CountDownLatch. MyWorkerThread definitely should not call publish() from a thread other than MySwingWorker without synchronizing access to any shared data. MyWorkerThread can update the GUI using invokeLater(), but the order won't be reliable.

Addendum: You asked the very practical question,

Do you have any reference for your answer, that [other] worker threads are not allowed to use publish()?

Memory Consistency Properties is a good summary. In effect, you would be calling publish() from multiple threads without synchronization. The results would be unpredictable.


There isn't any limitation on which Threads can call SwingWorker#publish().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜