Java-使用WeakHashMap做缓存

WeakHashMap使用WeakReference做WeakHashMap的Value。当key的引用被置为null的时候,map的内容会被很快gc。

package comz;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

class ObjectPoolClient {
	private static WeakObjectPool objectPool = new WeakObjectPool();

	public static void main(String args[]) throws Exception {
		BufferedReader reader = new BufferedReader(new FileReader("d:/a.txt"));
		List<String[]> parsedLines = new ArrayList<String[]>();
		String line;
		while ((line = reader.readLine()) != null) {
			String[] elements = line.split(",");
			for (int i = 0; i < elements.length; i++) {
				// replace the string read from the file with the pool instance
				elements[i] = (String) objectPool.replace(elements[i]);
			}
			parsedLines.add(elements);
		}
		reader.close();

		// Cool, we saved a lot of memory by reusing the repeated strings!
		doSomethingInteresting(parsedLines);
		// Now, we get rid of the references and soon the garbage collector
		// will reclaim the memory
		parsedLines = null;
		doMoreInterestingStuff();
	}
}
下面是pool的实现:

package comz;

import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * Oversimplistic implementation of an object pool
 */
public class WeakObjectPool {
	// Map where the key is an object, and the value is a weak reference
	// to the same object. We use the key to do the lookup, and the value
	// to actually return the object when it is found.
	private Map map = new WeakHashMap();

	public Object replace(Object object) {
		WeakReference reference = (WeakReference) map.get(object);
		if (reference != null) {
			System.out.println("direct return");
			Object result = reference.get();
			// Another null check, since the GC may have kicked in between the
			// two lines above.
			if (result != null) {
				return result;
			}
		}
		// If we got here it is because the map doesn't have the key, add it.
		System.out.println("add new one");
		map.put(object, new WeakReference(object));
		return object;
	}
}
It means that once you lose the last strong reference to an object that is working as a key in a WeakHashMap, the garbage collector will soon reclaim that map entry.

最重要的还是要知道自己i这做什么。使用WeakHashMap,当key被回收或者置为null,那么value也会很快被回收。

-------------------------------

所以,个人感觉,用WeakHashMap做缓存有点不靠谱。慎用!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值