I read in "Java Concurrency In Practice" that "publishing objects before they are fully constructed can compromise thread safety". Could someone explain this?
Consider this code:
public class World{
public static Point _point;
public static void main(String[] args){
new PointMaker().start();
System.out.println(_point);
}
}
public class Point{
private final int _x, _y;
public Point(int x, int y){
_x = x;
World._point = this;//BAD: publish myself before I'm fully constructed
//some long computation here
_y = y;
}
public void toString(){
return _x + "," + _y;
}
}
public class PointMaker extends Thread{
public void run(){
new Point(1, 1);
}
}
Because Point
publishes itself before setting the value of _y
, the call to println
may yield "1,0"
instead of the expected "1,1"
.
(Note that it may also yield "null"
if PointMaker
+ Point.<init>
don't get far enough to set the World._point
field before the call to println
executes.)
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