ReentrantLock
ReentrantLock (lightweight lock) can also call the object lock, reentrant lock mutex. synchronized heavyweight lock, JDK early version lock faster than synchronized, after the introduction of the biased locking JDK1.5 synchronized, lightweight and heavyweight lock lock. Performance matched that other kinds of locks, people like to see, tell us about the difference between this paper and lock the tryLock.
Lock VS TryLock
1 public void lock() { 2 sync.lock(); 3 } 4 5 public void lockInterruptibly() throws InterruptedException { 6 sync.acquireInterruptibly(1); 7 } 8 9 10 11 public boolean tryLock() { 12 return sync.nonfairTryAcquire(1); 13 } 14 15 16 public boolean tryLock(long timeout, TimeUnit unit) 17 throws InterruptedException { 18 return sync.tryAcquireNanos(1, unit.toNanos(timeout)); 19 }
One example is as follows:
If the thread A
and thread B
to use the same lock LOCK
, then thread A first acquire the lock LOCK.lock()
, and always hold not released. If at this time to go to B to acquire the lock, there are four ways:
-
LOCK.lock()
: This approach will always be in the waiting, even if the callB.interrupt()
can not be interrupted, unless the thread A call toLOCK.unlock()
release the lock. -
LOCK.lockInterruptibly()
: This approach will wait, but when the callB.interrupt()
will be interrupted to wait , and throwsInterruptedException
an exception, otherwise thelock()
same as always in waiting until the thread A releases the lock. -
LOCK.tryLock()
: There will not wait, get less lock and direct return false , to perform the following logic. -
LOCK.tryLock(10, TimeUnit.SECONDS)
: There will be in within 10 seconds of time waiting, but when the callB.interrupt()
will be interrupted to wait and throwInterruptedException
. Within 10 seconds if the thread A releases the lock, the lock will be acquired and returns true, otherwise it will get less than 10 seconds after the lock and returns false, to perform the following logic.
The difference between Lock and TryLock
1: lock not get the lock will wait. tryLock is to try and get returns false, to get returns true.
2: tryLock can be interrupted, interrupted, lock is not possible.