As suggested in several answers to this question:
What is the name of this locking technique?
I implemented a ReentrantReadWriteLock and saw a great speedup (I knew there was some lock contention in one my class and using a reentrant lock did help speed things up).
But now I am wondering: if inside a class all access (both reads and writes) are done by first locking either a read-lock or a write-lock, does it mean the synchronized keyword shouldn't be used anymore in that class?
For example, here's one official Java 1.6 example found at http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html
class RWDictionary {
private final Map<String, Data> m = new TreeMap<String, Data>();
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock r = rwl.readLock();
private final Lock w = rwl.writeLock();
public Data get(String key) {
r.lock();
try { return m.get(key); }
finally { r.unlock(); }
}
public String[] allKeys() {
r.lock();
try { return m.keySet().toArray(); }
finally { r.unlock(); }
}
public Data put(String key, Data value) {
w.lock();
try { return m.put(key, value); }
finally { w.unlock(); }
}
public void clear() {
w.lock();
try { m.clear(); }
finally { w.unlock(); }
}
}
There's no synchronize keyword.
Now I realize that one of the point of such locks is to be faster than other methods (in this case faster than synchronize) but what is the technical explanation behind this?
Does the use of a read-write lock in a class in every get/update method "replace" the synchronize keyword for these methods?