In my program I have two classes, one called GlassPiece, and one called TrackerChip.
These two objects are always “strongly connected”, that is, no two GlassPieces can share a TrackerChip, and no two TrackerChips can share a GlassPiece. Therefore in my setter methods, I need to take care to disconnect any old references hanging around, as so:
public class TrackerChip
{
GlassPiece linkedGlassPiece;
public void setGlassPiece(GlassPiece newGlassPiece)
{
GlassPiece oldGlassPiece = linkedGlassPiece;
linkedGlassPiece = newGlassPiece;
if(oldGlassPiece != null)
{
oldGlassPiece.setTrackerChip(null); //disconnect old GlassPiece
}
if(linkedGlassPiece != null && linkedGlassPiece.getTrackerChip() != this)
{
linkedGlassPiece.setTrackerChip(this); //update counterpart
}
}
}
and the method GlassPiece.setTrackerChip(TrackerChip) works exaxctly the same way.
The thing is, the above code doesn’t actually work, and strange stuff happens when trying to manage linking between several different GlassPieces and TrackerChips. However, if I replace the last part with:
if(newGlassPiece != null && newGlassPiece.getTrackerChip() != this)
{
newGlassPiece.setTrackerChip(this);
}
Then everything works properly. This seems very strange to me (all I did was replaced linkedGlassPiece, the instance variable, with newGlassPiece, the parameter). But early in the method I set the references equal to each other! Why does the first method not work?
P.S. I can confirm there is no infinite loop in the method.
As for why this isn’t working, you’re right, it won’t hit an endless loop, but it’s not going to do what you expect.
I honestly can’t think of a way to get it to work the way you’re going. You would have to add some additional parameters such that it would no longer be re-entrant. Namely, when you call setTrackerChip on the oldGlassPiece, it’s not going to turn around and call the same TrackerChip back setting its reference to null. Perhaps just a boolean flag that would indicate that it should not null out the second level references.
Here’s some code: