Search code examples
javamultithreadingconcurrencysynchronizationsynchronized

Does Synchronized Blocks maintain FIFO run order and can two blocks be reordered?


The first question is simple.

Say Java runtime has encountered three synchronized blocks with the same lock.

It sees bloc one first and grabs the lock and meanwhile it is running it encounters block two first and three next and both fail to obtain the lock.

Now block one finished and releases the lock so does this guarantee that block two will be the one to grab the lock and execute first since it tried to grab the lock before block three?

Next, say we have a method that has two synchronized blocks. Is it possible that block 1 which comes before block 2 might be reordered to run after block 2?

In the case they share the same lock, I am guessing the answer is no, but that might be wrong. Also what if they do not share the same lock?


Solution

  • synchronized blocks do not provide fairness guarantees which means that if thread A acquired lock and then threads B and C are waiting for the same lock there is no guarantee which of them will first acquire lock when thread A releases it. Also JIT compiler could decide to merge adjacent synchronized blocks which use the same lock object. Also JIT could remove synchronization if no other thread will ever use it like this

    synchronized (new Object()) {}
    

    https://www.ibm.com/developerworks/java/library/j-jtp10185/