How to safely publish mutable object from one thread to another

雨燕双飞 提交于 2019-12-24 13:24:30

问题


For example I have a mutable class Foo (or ArrayList for example) with no synchronization. Construction of such an object needs time so I'd like to perform it in a separate thread.

If I store the result of the computation somewhere and later access it from another thread, that would not be thread safe, because synchronization or volatile is required, right? (I am actually not quite sure here)

So I'm looking for a way to pass such an object from one thread to another without synchronizing of Foo.


回答1:


Your requirement matches the Producer Consumer Pattern. Java's concurrent package a offers thread-safe collections (Like BlockingQueue etc ). Producer will create the object and put it on BlockingQueue. The Consumer then picks up the object. Here is example implementation.




回答2:


first wonder if this is not something you can solve by creating a Future and getting the result later in the same execution thread. This would make everything very easy.




回答3:


You could also use a AtomicReference for that, take a look at this answer: When to use AtomicReference in Java?

Also take a look at here: Java Concurrency: CAS vs Locking

That said, concurrent programming is hard to to right. So i suggest you keep it as simple as possible, use the standard way java offers, synchronize on a common lock. If you notice that's the bottleneck you can always use another more sophisticated way afterwards.



来源:https://stackoverflow.com/questions/18444991/how-to-safely-publish-mutable-object-from-one-thread-to-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!