You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.9 KiB

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Cache<K, V> {
private final Map<K, V> 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<String, Integer> 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());
}
}