How reordering of instructions can cause concurrency issue

Viewed 224

I was reading about JMM (Java Memory Model) and I could understand that how flushing of the cache variables can cause other threads to have dirty reads. It was also mentioned that re-ordering of instructions can cause concurrency issues, even though I understood what is meant by re-ordering of the instructions I wouldn't understand how it can cause concurrency issues.

For example, suppose thread t1 has acquired lock while starting test1(), now even if compiler has done some optimization and there is some re-ordering because of which z = 4; has gone either up or down, now since t2 wouldn't get the lock for test2() until there t1 has released, so how re-ordering in test1() (and even in test2()) could cause concurrency issues/bugs?

public class Testing {
    private int z = 2;

    public synchronized void test1(){
        //some statement..
        z = 4;
        //some statement..
    }

    public synchronized void test2(){
        //some statement..
        System.out.println(z);
        //some statement..
    }
}


I understood that after proper synchronization re-ordering wouldn't cause the problem, but without synchronization even if compiler doesn't optimize and re-order still there are chances of concurrency issues, right? To be clear I was referring this link, I couldn't understand their point about concurrency issues after re-ordering, because like I said if there is no synchronization then concurrency issues can still arise even without any re-ordering.

EDIT: Please discard my code snippet because after looking at comments it doesn't hold good now, and my updated question is as above.

3 Answers
Related