import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Cache { private final Map store = new HashMap<>(); private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); public void put(K key, V value) { if (key == null || value == null) throw new IllegalArgumentException("Key and value must not be null"); lock.writeLock().lock(); try { store.put(key, value); } finally { lock.writeLock().unlock(); } } public V get(K key) { lock.readLock().lock(); try { return store.get(key); } finally { lock.readLock().unlock(); } } public boolean containsKey(K key) { lock.readLock().lock(); try { return store.containsKey(key); } finally { lock.readLock().unlock(); } } public V remove(K key) { lock.writeLock().lock(); try { return store.remove(key); } finally { lock.writeLock().unlock(); } } public void clear() { lock.writeLock().lock(); try { store.clear(); } finally { lock.writeLock().unlock(); } } public int size() { lock.readLock().lock(); try { return store.size(); } finally { lock.readLock().unlock(); } } public static void main(String[] args) { Cache cache = new Cache<>(); cache.put("one", 1); cache.put("two", 2); System.out.println(cache.get("one")); System.out.println(cache.get("two")); cache.remove("one"); System.out.println(cache.containsKey("one")); System.out.println("Cache size: " + cache.size()); } }