Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 81 inside the jvm Nested Locks One synchronized block can be nested inside another and it is perfectly possible for both blocks to synchronize on the same object monitor The HotSpot JVM is able to detect this case which we refer to as nested locks and it can remove the inner locks This removal is possible because a thread will acquire the lock as it enters the outer block and so will definitely still be holding it when the thread tries to enter the inner block At the time of writing the nested lock elimination in Java 8 appears to work only with locks that are declared as static final or with locks on this The following example shows an inner lock that is eliminated when nested synchronized blocks are encountered public class NestedLocks public static void main String args new NestedLocks private java util Random random new java util Random private static final Object lock new Object public NestedLocks long sum 0 for int i 0 i 1_ 000_ 000 i synchronized lock sum random nextInt synchronized lock sum random nextInt
You must have JavaScript enabled to view digital editions.