The class initialization procedure ensures that if the static field value is set using the static initializer (i.e. static variable = someValue; ), this value is displayed for all threads:
10 - If the execution of the initializers completed normally, then get the LC, mark the class object for C as fully initialized, notify all waiting threads, release the LC and complete this procedure in normal mode.
As for your editing, imagine a situation with two threads T1 and T2 running in this order from the point of view of a wall clock:
- T1:
Something s = Something.getInstance(); - T2:
Something s = Something.getInstance(); i = s.getAnswer(); Something s = Something.getInstance(); i = s.getAnswer();
Then you have:
- T1 gets LC, T1 starts
Something INSTANCE = new Something(); that initializes the answer returns T1 LC - T2 is trying to get LC, but already blocked T1 => is waiting. When T1 releases LC, T2 receives LC, reads
INSTANCE , then reads answer .
So, you can see that you have the right origin - before the relationship between writing and reading to answer , thanks to the LC lock.
source share