multithreading - Can the synchronized statements be re-ordered by Java compiler for optimization? -
can synchronization statements reordered. i.e : can :
synchronized(a) { synchronized(b) { ...... } }
become :
synchronized(b) { synchronized(a) { ...... } }
can synchronization statements reordered?
i assume asking if compiler can reorder synchronized
blocks lock order happens in different order code.
the answer no. synchronized
block (and volatile
field access) impose ordering restrictions on compiler. in case, cannot move monitor-enter before monitor-enter nor monitor-exit after monitor-exit. see grid below.
to quote jsr 133 (java memory model) faq:
it not possible, example, compiler move code before acquire or after release. when acquires , releases act on caches, using shorthand number of possible effects.
doug lea's jsr-133 cookbook has grid shows reordering possibilities. blank entry in grid means reordering allowed. in case, entering synchronized
block "monitorenter" (same reordering limitations loading of volatile
field) , exiting synchronized
block "monitorexit" (same storing volatile
field).
Comments
Post a Comment