Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

publishing objects and thread safety

I read in "Java Concurrency In Practice" that "publishing objects before they are fully constructed can compromise thread safety". Could someone explain this?

like image 584
Bogdan T. Avatar asked Feb 25 '12 21:02

Bogdan T.


1 Answers

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.)

like image 111
Matt McHenry Avatar answered Oct 14 '22 16:10

Matt McHenry