I was going through the JLS documentation on Thread and Locks http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5 .
class FinalFieldExample {
final int x;
int y;
static FinalFieldExample f;
public FinalFieldExample() {
x = 3;
y = 4;
}
static void writer() {
f = new FinalFieldExample();
}
static void reader() {
if (f != null) {
int i = f.x; // guaranteed to see 3
int j = f.y; // could see 0
}
}
}
I am confused with above example (ex no 17.5-1) mentioned in the section as to how f.y could be seen as zero. The Reader Threads will either read the object f as null in which case it will not execute anything or it will read the object f with some reference. If the object f has a reference then the constructor must have completed its execution even though Multiple Writer Threads are running so that a reference could be assigned to f and if the constructor has executed then f.y should be seen as 4.
In what condition can f.y =0 be possible?
Thanks
When race conditions occur. A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable.
Multithreading is the ability of a program or an operating system to enable more than one user at a time without requiring multiple copies of the program running on the computer. Multithreading can also handle multiple requests from the same user.
Assuming there are no more writes and all previous writes are visible to the current thread, then yes reading the value from multiple threads is safe.
The problems which occurs while using Collections in Multi-threaded application: Most of the Collections classes objects (like ArrayList, LinkedList, HashMap etc) are non-synchronized in nature i.e. multiple threads can perform on a object at a time simultaneously.
In what condition can f.y =0 be possible?
The Java memory model allows the JIT compiler to reorder initialization of non final fields outside the constructor. The x
field is final so it must be initialized by the JVM but y
is not final. So there is the possibility that the FinalFieldExample
is allocated and set on static FinalFieldExample f
but the initialization of the y
field has not been completed.
To quote from 17.5-1:
Because the writer method writes f after the object's constructor finishes, the reader method will be guaranteed to see the properly initialized value for f.x: it will read the value 3. However, f.y is not final; the reader method is therefore not guaranteed to see the value 4 for it.
Because f.y
is not final there is no guarantee that it has been set by the time the constructor finishes and the static f
is assigned. So there is a race condition created and the reader
may see y
as 3 or 0 depending on this race.
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