- biased: sometimes even in concurrent systems there’s no contention and JVM shouldn’t borrow mutex from OS for perform locking in this case. Hotspot can operate with its own internal data structures to simulate locking in more effective way. For example, if synchronized part of code is not executed concurrently in real time, JVM assigns an owner thread id to an object used as mutex in your Java code using CAS operation and additionally stores the reentrancy count if CAS is passed. It is biased lock – the ‘lightest’ type of locks done by JVM. Reentrancy count will be updated by lock owner thread just as usual local variable without CAS. If CAS fails it means another thread already gets this lock and in this case JVM stops the mutex owner thread, flushes thread context into the main memory and checks the reentrancy count. If it’s 0 JVM escalates lock to thin type otherwise to fat (I assume the main purpose is the wait time, it should be very small if lock is thin). Note Hotspot uses the same field for storing owner thread id in mutex object as for caching identity hash code. Thus if you retrieve identity hash code on you mutex once then it will be unavailable for biased locking even it was already used as biased. More info about biased locks is described in David Dice’s blog.
- thin: it’s a simple spin lock. It helps to save time for thread context switching when time for spinning is quite small. When one thread tries to acquire an occupied mutex it spins some time until the lock will be freed. The count of spins is based on internal JVM resolution and may depend from different factors: statistics gathered by JVM about your application, count of used threads, CPU and so forth. JVM determines when thin lock becomes inefficient and escalates it to fat lock.
- fat: the ‘strongest’ type of lock when JVM requests for an OS mutex and uses OS scheduler engine for threads parkings and wake ups. It is much costly than previous types because in this case JVM should directly interact with OS every time when thread acquires and frees the lock.
Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code
Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!
To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.