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
}
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With