Reputation: 732
Consider the following class:
public myClass {
int a;
Object obj; //This object is not of class myClass nor of a subclass of it.
void foo(int b){
synchronized(this){
print(a);
a = b;
obj.value = b;
obj.bar();
}
}
void bar(){
synchronized(this){
//Some code using obj here.
}
}
}
The Java documentations states:
When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquisition of the same lock.
Assume two threads T1, T2 and an object of myClass called myclass.
Now T1 calls foo, a short time after that T2 calls bar and eventually get's the lock and enters bar(). Correct me if wrong, but as far as I understand T2 see's changes done to variable a from T1.foo(b). How is it with changes done to obj? Consider this an arbitrary other object.
Is there an happens-before relationship guaranteed?
Upvotes: 2
Views: 589
Reputation: 692073
Yes: T2 acquires the lock that has been released by T1. So there's a happen-before relationship, and the writes done by T1 before releasing the lock are thus visible by T2 after it has acquired the lock.
See http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html#MemoryVisibility.
Note that it is about memory operations such as reads and writes of shared variables. Not only reads and writes of fields of the object being used as the lock.
Upvotes: 2