This only for learning the purpose, not intended for production usage.
I'm learning about memory barriers and trying to experiment with it. I have single CPU, multi-core system. I found out that two new memory-barrier related methods were introduced since Java 8. Now I wrote the following code and not quite sure about its thread-safety
private static final Unsafe U = //...
private int a = 0;
private int b = 0;
void foo(){
a = 1;
U.storeFence();
b = 1;
}
void bar(){
while( b == 0) continue;
U.loadFence();
assert(a == 1);
}
Now suppose we have 2-core CPU and two threads A
and B
. A
invokes foo
and B
invokes bar
. The load-store barrier Unsafe::loadFence
executes store buffer on each CPU core, therefore, thread B
should get the actual value of b
.
Can this assertion fail? Is it correct? If no, please could you clarify?