避免死锁
避免死锁
ReentrantLock
使用 tryLock() 方法来防止多线程死锁。
该示例启动两个线程。线程 1 首先获取 lock1 的锁,然后再获取 lock2 的锁;线程 2 首先获取 lock2 的锁,然后再获取 lock1 的锁。这样如果这时线程 1 获得了 lock1 的锁,同时线程 2 获得 lock2 的锁,然后线程 1 尝试去获得 lock2 的锁,线程 2 尝试获得线程 1 的锁,就会造成死锁。
public class DeadLock1 {
private static Lock lock1 = new ReentrantLock();
private static Lock lock2 = new ReentrantLock();
public static void deathLock() {
new Thread() {
@Override
public void run() {
while (true) {
if (lock1.tryLock()) {
try {
// 如果获取成功则执行业务逻辑,如果获取失败,则释放lock1的锁,自旋重新尝试获得锁
if (lock2.tryLock()) {
try {
System.out.println("Thread1:已成功获取 lock1 and lock2 ...");
break;
} finally {
lock2.unlock();
}
}
} finally {
lock1.unlock();
}
}
System.out.println("Thread1:获取锁失败,重新获取---");
try {
//防止发生活锁
TimeUnit.NANOSECONDS.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
if (lock2.tryLock()) {
try {
//如果获取成功则执行业务逻辑,如果获取失败,则释放lock2的锁,自旋重新尝试获得锁
if (lock1.tryLock()) {
try {
System.out.println("Thread2:已成功获取 lock2 and lock1 ...");
break;
} finally {
lock1.unlock();
}
}
} finally {
lock2.unlock();
}
}
System.out.println("Thread2:获取锁失败,重新获取---");
try {
//防止发生活锁
TimeUnit.NANOSECONDS.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 5; i++) {
deathLock();
}
}
}
我们这里使用 tryLock 来获取两个锁,如果一个线程不能同时获取两把锁,那么就回退并自旋重新尝试(使用 while 循环)。再使用 TimeUnit.NANOSECONDS.sleep(new Random().nextInt(100));随机休眠一段时间,从而降低发生活锁的可能性。如果处理成功,则使用 break 跳出循环。
使用 tryLock(long timeout, TimeUnit unit) 方法来防止多线程死锁。
tryLock(long time, TimeUnit unit)方法和 tryLock()方法是类似的,只不过区别在于这个方法在拿不到锁时会等待一定的时间,在时间期限之内如果还拿不到锁,就返回 false。如果一开始拿到锁或者在等待期间内拿到了锁,则返回 true。
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class DeadLock2 {
private static ReentrantLock lock1 = new ReentrantLock();
private static ReentrantLock lock2 = new ReentrantLock();
public static void deathLock() {
new Thread() {
@Override
public void run() {
while (true) {
try {
if (lock1.tryLock(10, TimeUnit.MILLISECONDS)) {
try {
//如果获取成功则执行业务逻辑,如果获取失败,则释放lock1的锁,自旋重新尝试获得锁
if (lock2.tryLock(10, TimeUnit.MILLISECONDS)) {
System.out.println("Thread1:已成功获取 lock1 and lock2 ...");
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(lock2.isHeldByCurrentThread()){
lock2.unlock();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(lock1.isHeldByCurrentThread()){
lock1.unlock();
}
}
System.out.println("Thread1:获取锁失败,重新获取---");
try {
TimeUnit.NANOSECONDS.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
try {
if (lock2.tryLock(10, TimeUnit.MILLISECONDS)) {
try {
//如果获取成功则执行业务逻辑,如果获取失败,则释放lock1的锁,自旋重新尝试获得锁
if (lock1.tryLock(10, TimeUnit.MILLISECONDS)) {
System.out.println("Thread2:已成功获取 lock2 and lock1 ...");
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(lock1.isHeldByCurrentThread()){
lock1.unlock();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(lock2.isHeldByCurrentThread()){
lock2.unlock();
}
}
System.out.println("Thread2:获取锁失败,重新获取---");
try {
TimeUnit.NANOSECONDS.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 5; i++) {
deathLock();
}
}
}
lockInterruptibly()
使用 lockInterruptibly()获得锁,如果发生死锁,调用线程 interrupt 来消除死锁。ReentrantLock.lockInterruptibly 允许在等待时由其它线程调用等待线程的 Thread.interrupt 方法来中断等待线程的等待而直接返回,这时不用获取锁,而会抛出一个 InterruptedException。而 ReentrantLock.lock 方法不允许 Thread.interrupt 中断,即使检测到 Thread.isInterrupted,一样会继续尝试获取锁,失败则继续休眠。只是在最后获取锁成功后再把当前线程置为 interrupted 状态。
public class DeadLock3 {
private static Lock lock1 = new ReentrantLock();
private static Lock lock2 = new ReentrantLock();
public static void deathLock() {
new Thread() {
@Override
public void run() {
try {
lock1.lockInterruptibly();
try {
TimeUnit.SECONDS.sleep(1);
lock2.lockInterruptibly();
System.out.println("thread 1 ...");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock2.unlock();
}
} catch (InterruptedException e1) {
e1.printStackTrace();
} finally {
lock1.unlock();
}
}
}.start();
new Thread() {
@Override
public void run() {
try {
lock2.lockInterruptibly();
try {
TimeUnit.SECONDS.sleep(1);
lock1.lockInterruptibly();
System.out.println("thread 1 ...");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock1.unlock();
}
} catch (InterruptedException e1) {
e1.printStackTrace();
} finally {
lock2.unlock();
}
}
}.start();
}
public static void main(String[] args) throws InterruptedException {
deathLock();
TimeUnit.SECONDS.sleep(2);
checkDeadLock();
}
//基于JMX获取线程信息
public static void checkDeadLock() {
//获取Thread的MBean
ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
//查找发生死锁的线程,返回线程id的数组
long[] deadLockThreadIds = mbean.findDeadlockedThreads();
System.out.println("---" + deadLockThreadIds);
if (deadLockThreadIds != null) {
//获取发生死锁的线程信息
ThreadInfo[] threadInfos = mbean.getThreadInfo(deadLockThreadIds);
//获取JVM中所有的线程信息
Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
for (Entry<Thread, StackTraceElement[]> entry : map.entrySet()) {
for (int i = 0; i < threadInfos.length; i++) {
Thread t = entry.getKey();
if (t.getId() == threadInfos[i].getThreadId()) {
//中断发生死锁的线程
t.interrupt();
//打印堆栈信息
// for (StackTraceElement ste : entry.getValue()) {
// // System.err.println("t" + ste.toString().trim());
// }
}
}
}
}
}
}
我们这里使用 lockInterruptibly()方法来获取锁,我们这里使用线程 1 获取 lock1 休眠 1 秒,嘻嘻按错 2 获取 lock2 休眠 1 秒,1 秒过后,然后线程 1 再获取 lock2,线程 2 再去获得 lock1 就会发生死锁。这是我们又执行了 checkDeadLock()方法,来检查 JVM 中是否有死锁,如果有死锁,则把发生死锁的线程执行 interrupt()方法,使该线程响应中断,从而避免发生死锁。(实际应用中,检查死锁可以单独开启一个 daemon 线程,每间隔一段时间检查一下是否发生死锁,如果有则预警、记录日志、或中断该线程避免死锁)