I. Lock and ReentrantLockLock provide an unconditional, round-robin, timed, and interruptible Lock acquisition operation. All locking and unlocking methods are explicit.
Public interface Lock {void lock (); // obtain the Lock. Void lockInterruptibly () throws InterruptedException; // obtain the lock if the current thread is not interrupted. Boolean tryLock (); // This lock is obtained only when the lock is idle. // If the lock is idle within the specified wait time and the current thread is not interrupted, the lock is obtained. Boolean tryLock (long time, TimeUnit unit) throws InterruptedException; void unlock (); // release the lock. Condition newCondition (); // return the new Condition instance bound to this Lock instance .}
Lock lock = new ReentrantLock (); lock. lock (); try {// update object status // catch exceptions and restore immutable conditions if necessary} finally {lock. unlock ();}
1. the round robin lock and the timed lock use tryLock to avoid lock sequence deadlocks
2. interrupted lock acquisition
public boolean sendOnSharedLine(String message) throws InterruptedException { lock.lockInterruptibly(); try { return cancellableSendOnSharedLine(message); } finally { lock.unlock(); }}private boolean cancellableSendOnSharedLine(String message) throws InterruptedException {}
3. Locking of non-Block Structures
Ii. Performance Considerations ReentrantLock provides better competitive performance in Java 5.0 than built-in locks. Java 6 uses an improved algorithm to manage built-in locks. Similar to the algorithm used in ReentrantLock, this algorithm effectively improves scalability.
Iii. Fairness ReentrantLock constructor provides two fairness options: unfair lock and fair lock. For Map performance testing, fair lock, unfair lock, ConcurrentHashMap.
4. Select between synchronized and ReentrantLock. When some built-in locks cannot meet the requirements, ReentrantLock can be used as an advanced tool. ReentrantLock should be used only when some advanced functions are required. These functions include: timed, round-robin and interrupt lock acquisition operations, fair queues, and non-block-structured locks. Otherwise, synchronized should be used first.
5. read-write lock
Java theory and practice: a more flexible and scalable locking mechanism in JDK 5.0