this the code in which i am trying to demonstrate nested lock problem,
import java.util.concurrent.locks.*;
class SharedResource{
private static final Lock lock = new ReentrantLock();
private void methodThree(String name,int x) throws Exception{
lock.lock();
while(x <= 15){
System.out.println("METHOD-THREE / THREAD-NAME : "+name+" NUM-VAL "+x);
x++;
Thread.sleep(250);
}
}
private void methodTwo(String name,int x) throws Exception{
lock.lock();
while(x <= 10){
System.out.println("METHOD-TWO / THREAD-NAME : "+name+" NUM-VAL "+x);
x++;
Thread.sleep(250);
}
methodThree(name,x);
}
public void methodOne(String name,int x) throws Exception{
try{
lock.lock();
while(x <= 5){
System.out.println("METHOD-ONE / THREAD-NAME : "+name+" NUM-VAL "+x);
x++;
Thread.sleep(250);
}
methodTwo(name,x);
}finally{
lock.unlock();
}
}
}
class MyRequestREQ extends Thread{
private SharedResource res;
private int num = 1;
MyRequestREQ(SharedResource res,String name){
super(name);
this.res = res;
}
@Override
public void run(){
try{
res.methodOne(Thread.currentThread().getName(),num);
}catch(Exception e){
System.out.println(e);
}
}
}
public class LockCountPractise{
public static void main(String [] args){
SharedResource resource = new SharedResource();
MyRequestREQ[] requests = new MyRequestREQ[]{
new MyRequestREQ(resource,"JACK"),
new MyRequestREQ(resource,"JILL"),
new MyRequestREQ(resource,"JASON")
};
for(int x=0; x < requests.length;x++){
requests[x].start();
}
}
}
but the output which i get is all the one run by the thread “JACK”, this thread prints till count 15, and just hung up.
Is the above program face a deadlock issue ?
do i need to unlock the lock in all of the methods of class SharedResource ?
Waiting for the suggestion.
you are not unlocking in method3 so when the first thread is done the others can’t go on since they can’t acquire the lock.
yes because every time you call
lock():see:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html#lock%28%29
as a suggestion: you can acquire the lock in method1 and release it in method3. so there will be 1 lock 1 unlock, you’ll be fine. no need to 3 lock-unlock cycle.
actually it depends what behaviour you want: