Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?
like image 578
Justin Avatar asked Mar 14 '26 06:03

Justin


1 Answers

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.

like image 153
assylias Avatar answered Mar 16 '26 20:03

assylias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!