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:
Dog, is Dog Thread safe (from visibility stand-point. Will T2 always see the same name and color as set by T1)?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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With