Here is my code
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class LockMap {
private final Map<String, String> map = new HashMap<>();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
public void put(String key, String value) {
try {
lock.writeLock().lock();
map.put(key, value);
} finally {
lock.writeLock().unlock();
}
}
public String get(String key) {
try {
lock.readLock().lock();
return map.get(key);
} finally {
lock.readLock().unlock();
}
}
}
Is this map wrapper actually threadsafe?
Especially, considering the array backing the HashMap
is not marked as volatile
, which guarantee do I have that a put
done by a thread is visible to another thread during a subsequent read?
I know that a ConcurrentHashMap
would be a much better choice over this simplistic wrapper
The goal of the question is to understand the impact of the lack of the volatile
keyword on the array backing the HashMap
implementation