Java Magazine, May/June 2018
Lock Elision in the JVM How the compilers escape analysis removes unnecessary locks ORACLE COM JAVAMAGAZINE MAY JUNE 2018 74 inside the jvm One of the optimizations made possible by escape analysis EA an analysis done by the compiler which we discussed in detail in our previous article is the removal of locks This removal can take place when it can be proved that the object on which a lock is acquired does not escape the local scope Such a situation means that the object can be accessed only by a single thread so there is no need to exclude other threads from accessing it Therefore the lock can be removed This is known as lock elision which is the topic of this article in our longrunning series on the mechanics of JVM operations An example of lock elision can be demonstrated using a well known thread safe class that uses synchronized methods java lang StringBuffer StringBuffer was included in Java 10 to allow more efficient concatenation of immutable string objects Each of its append methods is synchronized to enable the string under construction to be created safely when multiple threads are writing to the same StringBuffer object Many programs do not need this thread safety so in Java 5 the java lang StringBuilder class was introduced to provide an unsynchronized alternative to StringBuffer Both classes inherit from the package private java lang AbstractStringBuilder and have very similar implementations of append The main difference is the synchronization behavior of StringBuffer @ Override public synchronized StringBuffer append String str toStringCache null super append str BEN EVANS CHRIS NEWLAND BEN EVANS PHOTOGRAPH BY JOHN BLYTHE CHRIS NEWLAND PHOTOGRAPH BY DAVID NEWLAND
You must have JavaScript enabled to view digital editions.