Tuesday, March 26, 2013

Java Concurrency: Fair Lock

When use synchronized, the order of threads acquire a lock is not same as the order of threads request to acquire a lock.  If you want to have a fair lock mechanism, you should use Java 5 Lock.

java.util.concurrent.locks.ReentrantLock has a constructor with a boolean parameter. With this constructor, you can have fair lock mechanism.  ReentrantLock has a queue to contain threads which want to acquire this lock.  When a thread releases this lock, then the header will acquire this lock if the queue is not empty.

No comments:

Post a Comment