How to make thread-safe HashMap without locking `get()` method?

java, multithreading

Solution

try this

class MyClass<K, V> {
    private HashMap<K, V> map = new HashMap<K, V>();
    private ReadWriteLock rwl = new ReentrantReadWriteLock();
    private Lock rl = rwl.readLock();
    private Lock wl = rwl.writeLock();

    public V get(Object k) {
        rl.lock();
        try {
            return map.get(k);
        } finally {
            rl.unlock();
        }
    }

    public V put(K k, V v) {
        wl.lock();
        try {
            return map.put(k, v);
        } finally {
            wl.unlock();
        }
    }
}

Problem

I asked on interview a question: how to implement getter and setter for exclusive writing to `HashMap` and non-exclusive reading. Suppose following code: ``` public class MyClass { private HashMap map = new HashMap(); // HOW TO implement Getter and Setter for exclusive writing and non-exclusive reading } ```

Original source