java 引用之软引用与弱引用

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();
         }
     }
}

你可能感兴趣的:(软引用与弱引用,java 引用)