Mastering Java 11
上QQ阅读APP看书,第一时间看更新

Improved contended locking

The JVM uses heap space for classes and objects. The JVM allocates memory on the heap whenever we create an object. This helps facilitate Java's garbage collection, which releases memory previously used to hold objects that no longer have a memory reference. Java stack memory is a bit different and is usually much smaller than heap memory. 

The JVM does a good job of managing data areas that are shared by multiple threads. It associates a monitor with every object and class; these monitors have locks that are controlled by a single thread at any one time. These locks, controlled by the JVM, are, in essence, giving the controlling thread the object's monitor. So, what contends locking? When a thread is in a queue for a currently locked object, it is said to be in contention for that lock. The following diagram shows a high-level view of this contention:

As you can see in the preceding diagram, any threads in waiting cannot use a locked object until it is released.