Consider a snippet from a class :
// tail call to show
void showNextPoint(){
Point p = new Point();
p.x = 10;
p.y = 12;
show(p);
}
// multiple calls to show
void showPoints(){
Point p = new Point();
p.x = 10; p.y = 12;
show(p);
p.x = 20; p.y = 22;
show(p);
p.x = 30; p.y = 32;
show(p);
}
void show(Point p){
// use p in some way
// can p's state be changed safely ?
// can a new thread be started to work with p safely ?
}
In a multithreaded use-case , can the object p be considered as published safely from the showPoints() or showNextPoint() ? What conditions must hold true in show() for this ?
If show(Point p) is guaranteed 1) not to start a new thread and 2) not to change p’s state , can the showPoints() method be considered as safely publishing p ?
The
show()method gets a reference to aPoint p. If the caller afterwards makes a change top, it is making a change to the same Object. Ifshow()changespin any way then it is updating the samepobject that the caller is using. If a thread is forked that has thispthen you have a race condition as to which update topis performed in which order.You asked:
It cannot be changed safely without affecting the caller’s object, no. A new thread also cannot make changes to
pwithout it affecting the caller’s object when memory synchronization happens.It all depends on how you’ve written the code — what the contracts are. If a method makes changes to an object then it should be documented. If the caller does not wish this then either you should pass in a copy of a
Pointobject that the method could “own” or the method itself should copyPointitself.The complications around synchronizing changes to object is one of the reasons why many Java objects are immutable. You may consider doing this to
Point. Make it so thexandyvalues cannot be changed which means that theshowmethod and any threads it spawn can safely use the argument without worrying about changed being made to it from the caller.Edit:
@JohnVint had some better points about this but I thought I’d add my thoughts. I’m not sure what you are asking here and I’m not sure what you think “safely publishing” implies. The devil is in the details. If
show()doesn’t start a new thread then yes, the code you have posted will work and it’s okay to use the same mutablePointobject.Any method that takes an object argument but does not change the object in any way can say that it is “safely using” (I guess) the object. Since
showPoints()constructed the object and has the only reference to it then that is certainly safe as well. It’s whenpgets modified and there is another thread involved that everything changes.