Are Synchronized Methods Slower In Single Threaded Applications in Java
In this tutorial we are going to explore that Synchronized Methods Slower In Single Threaded Applications in Java.
Yes, single-theaded Java programs that use synchronization may be slightly slower than they would be without synchronization. For early Java releases, synchronization was expensive. For any modern release, however, uncontended synchronization is pretty cheap. I wouldn’t worry about this.
Note that Java 6 has and Java 7 is to have good optimizations around locking:
- Lock coarsening
- Lock elision
- Adaptive Spin locking
- Biased locking
For more information, see the Java SE 6 Performance White Paper. Also note that uncontended synchronization appears to be more expensive on multi-core CPUs than on single-core CPUs, perhaps due to the Java Memory Model requirements of synchronization forcing local CPU caches to be shared with other CPUs, or some other memory barrier.
When using synchronized data structures, the slowdown is not dependent on “how much” is getting blocked. The act of acquiring or releasing a lock is slow, as it usually involves something like a system call (context switches are slow on any platform). In a JIT environment like a typical JVM, it would theoretically be possible to optimize out all lock/unlock calls when there is only a single thread running, but it would have to be properly invalidated whenever another thread starts up.
Note that things like Linux’s futexes don’t have to make system calls unless there is contention, but using them is still slower than a no-op.