简体   繁体   中英

Java thread-hopping or inter-thread communication

I have a simple model-view-controller program. The model needs to be updated periodically, so the controller has a ScheduledThreadPoolExecutor that launches a Runnable with the required periodicity. The model's methods would be needed to be called within this Runnable.

Since the model is not thread-safe —and I would like to avoid having to make it thread-safe—, all the model's methods have to be called from the same thread in order to avoid concurrency problems.

What would be the best way to do this?

You could create a wrapper class with the same interface as the model. The wrapper class delegates calls to the ScheduledThreadPoolExecutor and returns the result.

You say it's a Java MVC program... does that mean you're synchronizing with the GUI thread? In that case you'd want to call SwingUtilities.invokeAndWait() or SwingUtilities.invokeLater() on your Runnable. That would run it on the GUI thread and avoid threading issues with the view.

Are there other, non-GUI, methods that also update the model?

The simplest way would be to synchronize on the model instance:

synchronized(myModel) {
  // periodical view update
}

It is, however, not best practice to synchronize a non-private object. So there is a good chance you'll get better ideas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM