2022-09-30

How to release Java ReentrantLock after sometime no matter what

My objective is to avoid thread deadlock or starvation. I have the following sample code for using ReentranLocks:

 class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m1() { 
     lock.lock();  // block until condition holds
     try {
       // ... method body
       // ... start doing the calculations here ...
     } finally {
       //Do not release the lock here, instead, release it in m2()
     }
   }
   public void m2() { 
     try {
       // ... method body
       // ... continue doing the calculations here
     } finally {
       lock.unlock()
     }
   }

 }

I know I can use tryLock() with a timeout, but I am thinking also to ensure it will be unlocked no matter what as the lock will start in m1() and will be unlocked in m2(). How to ensure it will be unlocked say after 3 seconds no matter what, as soon as I start the lock in m1()?

For the above to be successful, ie. without sending unlock request after 3 seconds, the caller or the user of the JavaBean must ensure calling m1() and then m2() immediately. This is a restriction I want to avoid, and if the programmer forgets to do that, it might result in spending a long time troubleshooting this issue, which is, why the system is getting in a deadlock.

Thoughts:

I am thinking to use Scheduled Tasks and Timers, will that work?



No comments:

Post a Comment