想象一下挤地铁的场景,两个200斤的大胖子都着急挤上地铁,双双卡在门口,这两人脾气都很犟,谁也不让谁。这是,每个人都拥有另一个人需要的空间,同时有占有对方需要的空间,每个胖子在挤上地铁前都不会让步—–死锁形成。
死锁描述的是这么一种情况:每个人都拥有其他人需要的资源,同时又等待其他人持有的资源,并且每个人在获得所有需要的资源之前都不会放弃已经拥有的资源。
Java编程当中,需要避免几种死锁情况:
- 锁顺序死锁
- 动态的锁顺序死锁
- 在协作对象之间发生的死锁
- 资源死锁
在死锁的监测恢复技术中,显式使用Lock类中的定时tryLock能使进程更平缓的死锁中恢复,而不用关闭整个进程。
tryLock
boolean tryLock(long time,
TimeUnit unit)
throws InterruptedException
Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted.
If the lock is available this method returns immediately with the value true. If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:
The lock is acquired by the current thread; or
Some other thread interrupts the current thread, and interruption of lock acquisition is supported; or
The specified waiting time elapses
If the lock is acquired then the value true is returned.
If the current thread:
has its interrupted status set on entry to this method; or
is interrupted while acquiring the lock, and interruption of lock acquisition is supported,
then InterruptedException is thrown and the current thread's interrupted status is cleared.
If the specified waiting time elapses then the value false is returned. If the time is less than or equal to zero, the method will not wait at all.
Implementation Considerations
The ability to interrupt a lock acquisition in some implementations may not be possible, and if possible may be an expensive operation. The programmer should be aware that this may be the case. An implementation should document when this is the case.
An implementation can favor responding to an interrupt over normal method return, or reporting a timeout.
A Lock implementation may be able to detect erroneous use of the lock, such as an invocation that would cause deadlock, and may throw an (unchecked) exception in such circumstances. The circumstances and the exception type must be documented by that Lock implementation.
Parameters:
time - the maximum time to wait for the lock
unit - the time unit of the time argument
Returns:
true if the lock was acquired and false if the waiting time elapsed before the lock was acquired
Throws:
InterruptedException - if the current thread is interrupted while acquiring the lock (and interruption of lock acquisition is supported)
FROM—Java Concurrency in Practice