Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 75 inside the jvm return this Compare that to the StringBuilder form @ Override public StringBuilder append String str super append str return this A thread calling an append method on a StringBuffer must acquire that objects intrinsic lock before entering the method and it must release the lock upon exit StringBuilder does not need to do this work so the class should outperform a StringBuffer at least based on first appearances After escape analysis was added to the HotSpot JVM calls to synchronized methods on objects such as StringBuffer can have their locks removed automatically This is possible only on objects that are created within the scope of a method and that can be shown not to escape Timing of Java operations is universally performed using the Java Microbenchmark Harness JMH Lets look at a JMH benchmark to see how modern JVMs can narrow the performance difference by eliding the StringBuffer locks when it can be proven that only a single thread can access the StringBuffer object @ State Scope Thread @ BenchmarkMode Mode Throughput @ OutputTimeUnit TimeUnit SECONDS public class StringBufferLockElision private static final String pieces new String a b c d e
You must have JavaScript enabled to view digital editions.