The class initialization procedure guarantees that if a static field's value is set using a static initializer (i.e. static variable = someValue;
) that value is visible to all threads:
10 - If the execution of the initializers completes normally, then acquire LC, label the Class object for C as fully initialized, notify all waiting threads, release LC, and complete this procedure normally.
Regarding your edit, let's imagine a situation with two threads T1 and T2, executing in that order from a wall clock's perspective:
- T1:
Something s = Something.getInstance();
- T2:
Something s = Something.getInstance(); i = s.getAnswer();
Then you have:
- T1 acquire LC, T1 run
Something INSTANCE = new Something();
, which initialisesanswer
, T1 release LC - T2 tries to acquire LC, but already locked by T1 => waits. When T1 releases LC, T2 acquire LC, reads
INSTANCE
then readsanswer
.
So you can see that you have a proper happens-before relationship between the write and the read to answer
, thanks to the LC
lock.