0

I have a quick question. I basically have a synchronized method which does some task when called upon so.

I use multi threads and sometimes, when the task is being executed by one thread, the thread hangs causing the synchronized method to be in blocked state indefinitely. This doesn't allow the next process to access the block.

Is there a way where I can set a timer, where after a said time ( say 60 seconds) the synchronized method gets released so other threads can still continue and not get blocked?

If there is a way, can someone please put up a sample code.

Thanks in advance!

Manohar
  • 39
  • 1
  • 9

1 Answers1

1

You can use a lock instead of synchronized keyword

To be able to forcefully unlock a lock owned by another thread, you can use following implementation https://stackoverflow.com/a/16492269/5313017

The method would be like following

    public void synchronizedMethod() {
        if(!lock.tryLock(10, TimeUnit.SECONDS)){
            lock.forceUnlock();
        }
        doStuff();
        lock.unlock();
    }
Saim Doruklu
  • 464
  • 2
  • 5
  • 16
  • Thanks. I think this is what I am looking for. One issue, there is not forceUnlock(); There is only lock.unlock() which doesn't interrupt or stop the other thread. It is in waiting state even after the set time. Is there something else like forceUnlock()? – Manohar Dec 05 '19 at 04:43
  • @Manohar this answer is suggesting to use the `Lock` proxy from the linked answer. Which I can only strongly advice against. This hack is broken in so many ways… – Holger Dec 05 '19 at 13:35
  • @Holger, what would you alternatively recommend? – Manohar Dec 06 '19 at 14:02
  • @Manohar when you think, you could force releasing a lock without encountering completely broken data structures, it’s an indicator that the code is holding the lock for too long. So you should fix the code to hold the lock only as long as necessary (that’s why id is called the “critical section” of the code). – Holger Dec 06 '19 at 14:10