欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 引用之软引用与弱引用

程序员文章站 2024-01-30 18:22:52
...
package cache;
 
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
 
public class WeakCache<K, V> {
    private final Map<K, Reference<V>> cache = new WeakHashMap<>();
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
 
    public void put(K k, V v) {
        lock.writeLock().lock();
        try {
            if (v != null) {
                cache.put(k, new WeakReference(v));
            } else {
                cache.remove(k);
            }
        } finally {
            lock.writeLock().unlock();
        }
    }
 
    public V get(K k) {
        lock.readLock().lock();
 
        Reference<V> value = cache.get(k);
        if (value == null) {
            return null;
        }
        V v = value.get();
        if (v == null) {
            lock.readLock().unlock();
            lock.writeLock().lock();
            try {
                cache.remove(k);
            } finally {
                lock.writeLock().unlock();
            }
        } else {
            lock.readLock().unlock();
        }
        return v;
    }
 
    public void clear() {
        lock.writeLock().lock();
        try {
            this.cache.clear();
        } finally {
            lock.writeLock().unlock();
        }
    }
}