0

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

Patanouk
  • 111
  • 8
  • In a brute-force sense, this would be a thread-safe usage of HashMap. However, the level of functionality present is a bit bare-bones (only `#get` and `#put`). `volatile` is not necessary in this scenario. What's the actual use-case? – Rogue Aug 15 '22 at 15:38
  • 1
    Lack of volatile is irrelevant. The locks provide the same happens-before guarantees. See the linked duplicate. Your impl is thread-safe. – Michael Aug 15 '22 at 15:44

0 Answers0