Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 80 inside the jvm 62 aload_ 2 63 monitorexit 64 aload 4 66 athrow 67 iinc 1 1 70 goto 11 Field java lang System out Ljava io PrintStream 73 getstatic 6 76 aload_ 0 77 getfield 4 Field sum J Method java io PrintStream println J V 80 invokevirtual 7 83 return The comment lines near the end of the listing each refer to the succeeding line of output Ed Recall that the relevant bytecodes for operating on intrinsic locks are monitorenter and monitorexit In the bytecode for each monitorenter instruction there are two monitorexit instructions each taking a different execution path This is because the first monitorexit releases the monitor upon a normal exit from the locked region and the second monitorexit releases the lock upon an abnormal exit from the region This set of bytecodes might look odd because in the source code the only operation performed within the synchronized region is an increment to a primitive int variable This action cannot throw an exception but there is a possibility of an abnormal termination of the locked region That can occur if the thread receives an InterruptedException if for instance the stop method were invoked on the executing thread For this reason there is a second path to ensure the monitor is always released even in the event that an unchecked exception is thrown You can read more about this in the JVM specification The lock coarsening optimization is enabled by default but can be disabled using the VM switch XX EliminateLocks
You must have JavaScript enabled to view digital editions.