ALL > Computer and Education > courses > university courses > undergraduate courses > Operating System > zstu-(2021-2022)-1 >
2019529628011_ENOCH KWATEH DONGBO_Homework#7 Version 0
👤 Author: by enochdongbogmailcom 2021-12-09 02:51:58
Question: Describe your own example which may encounter deadlocks. a. show that the four necessary for deadlock indeed holds in this example. b. state a simple way for avoiding deadlocks in this case.

 

Solution:

In this example,

 

 

public class DieLock{

public static Object t1 = new Object();

public static Object t2 = new Object();

publict static void main(String[] args){

new Thread(){

@Override

public void run(){

synchronized(t1){

System.out.println("Thread1 get t1");

 

try{

Thread.sleep(100);

}catch (Exception e){

}

synchronized(t2){

System.out.println("Thread2 get t2");

}

}

}

}.start();

new Thread(){

@Override

public void run(){

synchronized (t2){

System.out.println("Thread2 get t2");

 

try {

Thread.sleep(100);

} catch (Exception e){

}

synchronized (t1){

System.out.println("Thread2 get t1");

}

}

}

}.start();

}
}

 

a. I figure out from the problem that both wait for each other to release the lock they hold, and then wait until death. Likewise,

b.  When it comes to avoiding deadlock;

Avoid one thread acquiring multiple locks at the same time;

Avoid a thread occupying multiple resources in the lock at eh same time, and try to ensure that each lock occupies only one resource;

Try timing lock, use lock.tryLock(timeout) instead of using an internal locking mechanism;

Tor database lock, locking, and unlocking must be in one database connection,  otherwise, unlocking failure will occur.

Please login to reply. Login

Reversion History

Loading...
No reversions found.