软饮用,弱引用一般可以实现内存敏感型缓存。当软引用指向的对象被回收时,会将软饮用加入引用队列。
/**
* 设置最大堆内存. -Xmx20m
*/
public class Test {
static final int _4M = 4 * 1024 * 1024;
public static void main(String[] args) throws InterruptedException {
List<SoftReference<byte[]>> list = new ArrayList<>();
ReferenceQueue<byte[]> referenceQueue = new ReferenceQueue();
for(int i = 0; i < 5; i++){
SoftReference<byte[]> reference = new SoftReference<>(new byte[_4M], referenceQueue);
list.add(reference);
}
Reference poll = referenceQueue.poll();
while (poll != null){
list.remove(poll);
poll = referenceQueue.poll();
}
for (SoftReference<byte[]> reference : list) {
System.out.println(reference.get());
}
}
}