How will we use try for Lock.lock and Lock.unlock

Consider the following code. To prevent an IndexOutOfBoundsException when calling listIterator , we use a reader lock to retrieve the index based on iteartor and lock the else write, where is the write operation on stockCodes .

Note that we did not use the locking mechanism to iterate using listIterator , since it is from CopyOnWriteArrayList . No lock is required, as ConcurrentModificationException should not be thrown.

 // stockCodesReaderLock is reader lock from java.util.concurrent.locks.ReadWriteLock // stockCodes is CopyOnWriteArrayList // Acquire iterator in a safe way. stockCodesReaderLock.lock(); final int stockCodesSize = stockCodes.size(); if (currIndex < stockCodesSize) { listIterator = stockCodes.listIterator(currIndex); } stockCodesReaderLock.unlock(); 

I was wondering if I should have a try/finally block since I don't see the possibility of an exception being thrown? If try/finally is mandatory, should I use (A) or (B) ?

Is there a need for me?

(A)

 try { stockCodesReaderLock.lock(); final int stockCodesSize = stockCodes.size(); if (currIndex < stockCodesSize) { listIterator = stockCodes.listIterator(currIndex); } } finally { stockCodesReaderLock.unlock(); } 

(IN)

 stockCodesReaderLock.lock(); try { final int stockCodesSize = stockCodes.size(); if (currIndex < stockCodesSize) { listIterator = stockCodes.listIterator(currIndex); } } finally { stockCodesReaderLock.unlock(); } 
+5
source share
2 answers

Other respondents are right: you should always use try / finally.

Regarding the correctness of (A) or (B), Sun seems to recommend (B) in the JavaDoc ReentrantReadWriteLock (search β€œfinally” to see this). I believe this is because the lock() method may throw an exception if it fails: for example, JavaDoc says that it will throw an Error in the unclear case when the same thread tries to get the lock recursively more than 65535 times.

+11
source

This is good defensive programming. If your code ever changes so that the body throws an exception for any reason (including, for example, OutOfMemoryError), you will be glad that you did not leave the lock in a stuck state.

I would personally go (B) - if the lock () method were to throw an exception, it would still be balanced. But in practice, I do not think this is so important.

+6
source

Source: https://habr.com/ru/post/894341/