最近想对一些频繁访问且实时性不敏感的数据进行一个缓存,原本是想用HashMap做的,后来发现有个叫WeakHashMap的东西,看介绍貌似更适合我这个场景,我希望达到的是这样的效果:
需要取数据时向缓存管理器请求,当缓存管理器在缓存(HashMap或者WeakHashMap)中没有取到数据则从数据库读取数据放入缓存然后返回该数据。然而,保存在缓存中的数据仍然接受GC的管理,即它可以被GC清除。但是我在网上查到的资料,对于WeakHashMap的实现方式有两种说法,不知道哪种才是对的:
一、WeakHashMap中有expungeStaleEntries方法,在进行一些特定操作的时候,它会自动调用该方法,清除没被引用的数据。(我查看过它的源代码,确实调用了该方法,但是主要是看不懂这个方法里面做了什么)
二、WeakHashMap里面使用的是弱引用,允许被GC清除。(可是我在源代码里面没有看到弱引用相关的代码啊)我想,如果是后者,我的目的可能就可以实现了。我的目的就是说,我只管往里面放数据,不管清除,当GC发生时会自动将不需要的数据清除。这里有一个重要的点:并不是该对象一失去引用就立即(或在下次调用时立即)被清除,(这样的话缓存就没有任何意义了),而是内存不足时就像弱引用一样被GC清除(GC的发生是程序无法预测的)弱引用WeakHashMapGC缓存内存

解决方案 »

  1.   

    有个内部类,内部类继承了WeakReference private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {
            private V value;
            private final int hash;
            private Entry<K,V> next;
      

  2.   

    貌似是的哦,那它那个expungeStaleEntries方法是做什么用的呢?我没看懂,感觉只要用的是弱引用不就可以自动回收了么?它是说在对象被列入GC的清除列表(ReferenceQueue)后把对象的索引从WeakHashMap中移除么?ReferenceQueue与GC是什么关系?是不是列入ReferenceQueue了就代表已经回收了,还是代表即将回收?对于ReferenceQueue里的对象,是否意味着它已经“死”了,从里面不可能再取出它的各个字段值了?另外,顺问,你是下载了jre源代码查看的还是用反编译工具查看class文件的?貌似我的jad不支持泛型,所有与泛型相关的部分都没有了,比如你给的那段,我这边是这样的:    private static class Entry extends WeakReference
            implements Map.Entry        Object value;
            int hash;
            Entry next;
      

  3.   

    源码都在jdk的安装目录下有,叫src.zip。如果你英语够好看api说明,如下。
    Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations. Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class, and has the same efficiency parameters of initial capacity and load factor. Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method. This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated, so it is impossible to do a lookup of that key in a WeakHashMap at some later time and be surprised that its entry has been removed. This class will work perfectly well with key objects whose equals methods are not based upon object identity, such as String instances. With such recreatable key objects, however, the automatic removal of WeakHashMap entries whose keys have been discarded may prove to be confusing. The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, and the entry set to yield successively smaller numbers of elements. Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it, both inside and outside of the map, have been cleared by the garbage collector. Implementation note: The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys, either directly or indirectly, since that will prevent the keys from being discarded. Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is, a value object may strongly refer to some other key object whose associated value object, in turn, strongly refers to the key of the first value object. One way to deal with this is to wrap values themselves within WeakReferences before inserting, as in: m.put(key, new WeakReference(value)), and then unwrapping upon each get. The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
    如果看不懂,搜搜翻译的。
      

  4.   

    关联下源码,再点击class就是java类了。
      

  5.   

    网上查到的资料很清楚的解释了WeakHashMap到底做了些什么,这里摘抄下来方便后人
    http://blog.csdn.net/coolwxb/article/details/7939246