0

I'm facing a problem while acquiring write lock and then do some operation using ReentrantReadWriteLock

There are two classes say ClassA and ClassB ClassA is holding write lock ClassB is having read lock

public static final ReentrantReadWriteLock lock=new ReentrantReadWriteLock(); //defined in singleton class

ClassA{

 public void onMessage(Message msg){
  if(update is received from UI){
   lock.writeLock().lock();
   try{
     //critical code here
   }finally{
     lock.writeLock().unlock();
   }
 }
}
}

ClassB{
public void onMessage(Message msg){
  if(NO update is received from UI){
   lock.readLock().lock();
   try{
     //critical code here
   }finally{
     lock.readLock().unlock();
   }
  }
 }
}

There is an UI where in user can update/create, when this event happens i am activating write lock in ClassA, so that readers of ClassB be blocked.

but for some strange reason, ClassA is waiting(infinitely) to acquire Write lock!!

Can we reset all the lock acquired by different threads and then acquire write lock ? please suggest if there is another way around..

Nitesh Jain
  • 177
  • 2
  • 13
  • It's not the classes that are holding the locks, it's the thread that's currently executing the code. Locks are not designed to prevent different users from changing their data. – f1sh Mar 30 '16 at 13:32
  • 2
    If the `// critical code here` sections of your code are doing work and never finishing, the locks will never be released. That is where I would look first. – Sean Bright Mar 30 '16 at 13:33
  • I agree @SeanBright, if critical section doesn't complete, threads holding locks wont be released. so i added logger once i acquire read lock("acquired lock") and before its released in finally block ("releasing lock") and when i checked the log files, i can see that the number of "acquired lock" and "releasing lock" are equal, this mean lock were released, even then there was writers starvation! – Nitesh Jain Mar 31 '16 at 05:29

0 Answers0