Pergunta

As title says, curious what happens to the readwritelock when the current thread crash.

 readlock.lock();
 try {
    ...
 } finally {
   readlock.unlock();
 }

We can definitely unlock in the finally block to prevent any abruption. But what if the readLock.lock() statement crashes, does the lock automatically released?

Thanks,

Foi útil?

Solução

  • If readlock.lock throws exception.
  • Lock operation fails.
  • No lock is being acquired.
  • No unlock is required.

If run-time exception being thrown during readlock.lock, yet lock is being acquired. lock author is implementing it wrongly. You may file a bug report for the author :)

Outras dicas

If you refer to java.util.concurrent.locks.ReentrantReadWriteLock class then crash of a thread just after readlock.lock() (readlock.unlock() has not been called) will not release the read lock.

It is different with write lock though. A write lock defines an owner and can only be released by the thread that acquired it. In contrast, the read lock has no concept of ownership, and there is no requirement that the thread releasing a read lock is the same as the one that acquired it.

I would suggest putting readlock.lock() into try-finally statement.

It depends on your implementation of 'readlock' variable and 'how did your thread crash'. As far as I can see 'readlock' variable can be of any type, and there are multiple way a thread can crash.

For your information only, each java objects has a 'monitor'. If what you need is to synchronize access to shared variable by multiple threads, I suggest you spend some time with this chapter of java tutorial: http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top