Java%20garbage%20collector%20collection%20question.%20If%20I'm%20holding%20a%20reference%…
- User
Java%20garbage%20collector%20collection%20question.%20If%20I'm%20holding%20a%20reference%20to%20an%20object%20(A)%20that%20itself%20holds%20a%20reference%20to%20another%20object%20(B)%2C%20and%20I%20pass%20A%20into%20another%20thread%2C%20but%20then%20afterwards%20B%20is%20changed%20to%20C%2C%20does%20the%20new%20thread%20see%20B%20or%20C%3F
- Assistant
In Java, when you pass object
Ainto another thread, that thread receives a reference to the sameAobject that the original thread was holding. IfAholds a reference to objectB, the new thread can accessBthrough that reference.However, if afterward you change the reference held by
Ato a new objectC(e.g.,A.setB(C)), whether the new thread seesBorCdepends on how the reference toBwas changed.-
If you modify
Adirectly to point toC: If the thread that receivedAseesB, it won’t seeCunless it re-evaluates or accessesAafter the change. This means if the new thread accessesAafter you updated it, it will seeC; otherwise, it will continue to seeB. -
If you change the state of
Bto createC: IfBhas mutable state and you’re changing some properties ofBinstead of changing whatAreferences, both threads will still reference the sameBobject. If you changeBto have the characteristics ofC(e.g., updating its properties), the new thread will see those updates as long as the new thread accessesBdirectly.
In summary:
- If you change the reference of
BinAtoC, the new thread will still see the old referenceBunless it accessesAafter the update to seeC. - If you change the contents/state of
Bto representCbut do not modify the reference inA, both threads will see the modified state ofB.
Note on Thread Safety
Be cautious when updating shared data or references across threads, as doing so without proper synchronization can lead to visibility issues. Using volatile variables, synchronized blocks, or other concurrency controls is often necessary to ensure that changes made by one thread are visible to others.
-