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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With