Home >Java >javaTutorial >Detailed explanation of explicit locks in java concurrent programming
Lock provides an unconditional, pollable, timed and interruptible lock acquisition operation. All locking operations and unlocking methods are explicit
ReentrantLock implements Lock: and provides the same memory semantics as synchronized; it also provides reentrant locking semantics
void LockDefinition() { Lock lock = new ReentrantLock();try {//do someting//更新对象状态,捕获异常;并在必要时恢复不变性条件} finally {//finally中释放锁 lock.unlock(); } }
lock.tryLock([Long,TimeUnit]): Try to acquire the lock, and the time is a timed lock
lock.lockInterruptibly();
ReentrantLock can create fair locks (requested sequential acquisition of locks) and unfair locks (queue-breaking).
Queue jumping: When a thread requests an unfair lock, if the status of the lock is available when the request is made, then the thread will not be put into the queue, but will skip all waiting threads in the queue and obtain the lock;
Note: Unfair locks do not advocate queue jumping, but they cannot prevent queue jumping; fair locks will be placed in the queue and executed sequentially
Unfair locks are faster than fair locks when competition is fierce Fast: The reason is that there is a serious delay between resuming a thread in the queue and the thread starting to run
ReentrantLock is a standard mutex lock, but In some scenarios such as: parallel reading and reading cannot be achieved
ReadWriteLock read-write lock: implement ReentrantReadWriteLock: method readLock read lock and writeLock write lock
Release priority: When a write lock is released, and there are both reads and writes in the queue, should the read, write, or the thread that sends the request first be given priority?
Read thread jumps in the queue: There is a write lock waiting for the current read lock, so should the subsequent read lock jump in the queue and read directly? Direct reading will improve concurrency but may result in write starvation and failure to obtain
Reentrancy: Are read locks and write locks reentrant?
Demotion: Write lock, can you acquire a read lock without releasing the lock, so that the thread's lock can be downgraded?
Upgrade: Can read locks be upgraded to write locks before other waiting threads? If two threads try to upgrade to write locks at the same time, it is easy to cause a deadlock
Applicable to: data structures that mainly read operations
The above is the detailed content of Detailed explanation of explicit locks in java concurrent programming. For more information, please follow other related articles on the PHP Chinese website!