Nulldevice
Nulldevice

Reputation: 4006

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
}

Upvotes: 5

Views: 318

Answers (2)

auselen
auselen

Reputation: 28087

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
}

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234815

If val was marked final (which would also prevent a subsequent assignment to null) then an NPE would not be possible:

public final MyClass val = new MyClass();

Otherwise, yes, your code is brittle.

Upvotes: 3

Related Questions