Justin
Justin

Reputation: 2365

MultipleThreads and synchronization Thread Visibility

Say I have a Thread T1. I create an object in that thread e.g. Dog and set some properties (name, color) etc.

I then thread another Thread T2 (from T1) and pass the Dog object to it. After this point, T1 doesn't change anything properties of the object and doesn't even want to read it, but holds onto the actual reference (Dog d).

Question:

  1. Assuming T2 doesn't change anything in Dog, is Dog Thread safe (from visibility stand-point. Will T2 always see the same name and color as set by T1)?

Upvotes: 3

Views: 110

Answers (4)

Erik Kaju
Erik Kaju

Reputation: 3173

As long as:

  • your implementation guarantees being free of race conditions when accessing properties of your Dog d object by multiple threads simultaneously

or

  • Dog d's properties' access is protected from race conditions

... you can consider it to be thread safe.

I would say that right now it is not possible to say whether your solution is thread safe or not. Because nothing is mentioned about data accessing principles or locks.

I suspect it is not thread safe!

Upvotes: 0

assylias
assylias

Reputation: 328735

Every actions in a thread can see whatever happened before that thread was started. In your example, T2 is guaranteed to see all changes made by T1 before t2.start() was called.

That does not make Dog thread safe but your use of that class is thread safe.

Note however that any subsequent changes made by either T1 or T2 after that point are not guaranteed to be visible from the other thread.


Reference: JLS #17.4.5:

A call to start() on a thread happens-before any actions in the started thread.

Upvotes: 2

Nick
Nick

Reputation: 1340

"is Dog Thread safe?" If its not immutable then I'd say no.

"from visibility stand-point. Will T2 always see the same name and color as set by T1?" Probably. (watch out if things are not volatile or synchronized.

Simple way to handle this is to synchronize on it. that will make it thead-safe.

Upvotes: -1

Maurício Linhares
Maurício Linhares

Reputation: 40333

Dog is thread safe only if the values are just instance variables and volatile.

If they are not volatile there is a chance that T2 could read stale data.

Upvotes: 1

Related Questions