Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

End of constructor as happens - before relation in Java

Do I understand right that end of constructor is not a happens - before relation in Java? Is it possible, that code below with threads A and B not been synchronized somehow could throw a NullPointerException ?

// Shared reference declaration
public MyClass val;

// Class declaration
public class MyClass {
    public Object object;
    public MyClass() {
        object = new Object();
    }
}

// Using in thread A
MyClass loc = new MyClass();
val = loc;

// Using in thread B
if(val != null) {
    val.object.hashCode(); // IMO could throw NPE
}
like image 530
Nulldevice Avatar asked Jun 09 '14 08:06

Nulldevice


1 Answers

If it was

 val.object.hashCode();

then there was a possibility of NPE, since while thread B may see val = loc it may not have seen object = new Object(); yet due to cache behaviour on different cores etc. which is allowed by Java's weak memory model for performance reasons.

I don't think your original code can throw NPE since if val is not null then hashCode will execute.

if(val != null) {
    val.hashCode(); // IMO could throw NPE
}
like image 66
auselen Avatar answered Nov 07 '22 09:11

auselen