IUnknown
IUnknown

Reputation: 9819

Publishing immutable

Immutable objects can be published through any mechanism-Effectively immutable objects must be safely published(static initialization,volatile etc) - 'Java Concurrency in practice'.

class A{//immutable
    final int i;
    a(int i){
        this.i=i;
    }
    public int getI(){
        return i;
    }
} 

class B{
    A a=null;
    public A getA(){
       if(a==null){ 
           a= new A(10);
       }
       return a;
   }
}

If instance of B is shared between threads;wouldn't there be a possibility of a partially constructed A leaking out - though it is immutable.
Or have I understood this wrong?

Upvotes: 0

Views: 95

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533750

A will be correctly constructed as all it's fields are final. The problem you have is there is a race condition on getA() as it is lazy, but not thread safe. i.e. it is possible for different threads to call this and return different objects. The objects will be complete and correct but not be the same one which may have been the intent. Consider the following

T1: if (a == null)
T2: if (a == null)
T3: if (a == null)
T1:     a = new A();
T1: return a;
T2:     a = new A();
T2: return a;
T3:     a = new A();
T3: return a;

All three threads return a different object.

Upvotes: 1

Related Questions