Search code examples
javajava.util.concurrentjava-threads

Overcoming Improper Publication in Java


I came across the below class in the book "Java concurrency in practice". The author states that the state of the Holder can be stale in the below example resulting in AssertionError when assertSanity is called. How can the below Holder class be made Immutable to overcome this?

public class Holder{

  private int n;

  public Holder(int n) { this.n = n;}

  public void assertSanity() {
     if(n != n)
          throw new AssertionError(" this statement is false");

  }

}

//unsafe publication
public Holder holder;

public void initialize(){
     holder = new Holder(42);
}

Solution

  • To make the Holder class immutable, simply change

      private int n;
    

    to

      private final int n;
    

    You could also add a public (non-synchronized) getter method for the Holder.n field, if you wanted to. There isn't a lot of point having a private field that nothing can use.

    (But get rid of assertSanity because it is of no earthly use.)

    When you have done the above, Holder will be immutable with respect to the n field, and you won't have to worry about unsafe publication of that field.