Brian Reischl
Brian Reischl

Reputation: 7356

Does using ReadWriteLock inside a synchronized method make sense?

We have some code that implements a cache. All of the methods have the synchronized keyword, and also use a ReadWriteLock internally. Simplified example:

private final ReadWriteLock _rwLock = new ReadWriteLock();

public synchronized void setItem(final UUID id, final Object someObjToCache) {

    try {
        _rwLock.writeLock().lock();
        _innerCache.set(id, someObjToCache);
    } finally {
        _rwLock.writeLock().unlock();
    }
}

public synchronized Object getItem(final UUID id) {

    try {
        _rwLock.readLock().lock();
        return _innerCache.get(id);
    } finally {
        _rwLock.readLock().unlock();
    }
}

Is there any benefit to using both of these locking techniques? I expect it to be a read-mostly cache, so I would think that just using the ReadWriteLock would be sufficient.

Upvotes: 1

Views: 122

Answers (2)

kraskevich
kraskevich

Reputation: 18566

Yes, a ReadWriteLock should be sufficient. Using it with synchronized does not make much sense in this case: synchronized means that only one thread can execute any synchronized method at a time.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533670

Using two locks will only help when you need to lock two resources at once.

I suspect you only need one lock, not two. If you used a concurrent collection you might not need either.

final Map<UUID, Object> cache = new ConcurrentHashMap<>();

public void setItem(UUID id, Object obj) { cache.put(id, obj); }
public Object getItem(UUID id) { return cache.get(id); }

Upvotes: 1

Related Questions