Do the following Java programs have to print “num: 1 m_i: 2” because of the synchronization sequence
I just want to check whether I understand the thread start synchronization rule of JMM correctly:
Do the following Java programs have to print "num: 1 m_i: 2" because of the following synchronization sequence
http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.4.4
The operation of the starting thread is synchronized with the first operation in its starting thread
public class ThreadHappenBefore { static int num; int m_i; public static void main(String[] args) { final ThreadHappenBefore hb = new ThreadHappenBefore(); num = 1; hb.m_i = 2; new Thread(new Runnable() { @Override public void run() { System.out.println("num:"+num); System.out.println("m_i:"+hb.m_i); } }).start(); } }
resolvent
Solution
When early code affects later code, anything encoded before other code is guaranteed to occur before other code in a given thread Because threads start coding after assignment and assignment will affect the result of print statement, these assignments are "visible" (i.e. occurred before) of the code printing them
However, when viewed from another thread, there is no such guarantee of the impact on the execution order
Edited (thanks to reviewers)
Added the above refinement (BOLD) for reordering