Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 614
WelcomeTo Avatar asked Mar 31 '13 12:03

WelcomeTo


1 Answers

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();
        }
    }
}
like image 188
Evgeniy Dorofeev Avatar answered Oct 10 '22 16:10

Evgeniy Dorofeev