Korniltsev Anatoly
Korniltsev Anatoly

Reputation: 3686

How to safely publish mutable object from one thread to another

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.

Upvotes: 1

Views: 626

Answers (3)

Ortwin Angermeier
Ortwin Angermeier

Reputation: 6193

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.

Upvotes: 0

Dieter
Dieter

Reputation: 21

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.

Upvotes: 1

Santosh
Santosh

Reputation: 17913

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.

Upvotes: 1

Related Questions