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(); }
source share