Why CopyOnWriteArrayList use ReentrantLock but ReentrantReadWriteLock?

151 views Asked by At

This is the code to add the element, Why not use ReentrantReadWriteLock but ReentrantLock

 public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
               //add element 
        } finally {
            lock.unlock();
        }
}
1

There are 1 answers

1
Stephen C On

The whole point of the CopyOnWriteArrayList implementation is that read operations do not do any locking at all.

So since only write operations need locking, and they all need to acquire an exclusive lock, it it simpler and more efficient to use the ReentrantLock class here.