标签:style blog http color io os 使用 ar java
>>>>here is about java.lang.ref
包含具体的实现
该动作由VM执行,当没有Strong Reference引用的时候,在下一个回收周期会被回收
该动作由put, remove, get方法触发
基于ReferenceQueue监视哪些key已经被回收,随着上述方法的触发以回收过期的元素
1 private void expungeStaleEntries() { 2 Entry<K,V> e; 3 while ( (e = (Entry<K,V>) queue.poll()) != null) { 4 int h = e.hash; 5 int i = indexFor(h, table.length); 6 7 Entry<K,V> prev = table[i]; 8 Entry<K,V> p = prev; 9 while (p != null) { 10 Entry<K,V> next = p.next; 11 if (p == e) { 12 //兼容第一个元素 13 if (prev == e) 14 table[i] = next; 15 else 16 prev.next = next; 17 //删除值 18 e.next = null; // Help GC 19 e.value = null; // " " 20 size--; 21 break; 22 } 23 //删除关于entity的引用 24 prev = p; 25 p = next; 26 } 27 } 28 }
WeakHashMap并不是一个有用的缓存,至少并不是像大多数人想的或者网上那些奇怪的文章中介绍的那样。
原因包括以下两个:
WeakHashMap is mostly useful to keep metadata about objects whose lifecycle you don‘t control
它适用于保存一些关于你所需要的对象的额外信息,而且这些额外信息你不想控制他们的生命周期
Lets say you want to associate some extra information to an object that you have a strong reference to.
You put an entry in a WeakHashMap with the object as the key, and the extra information as the map value. Then, as long as you keep a strong
reference to the object, you will be able to check the map to retrieve the extra information. And once you release the object, the map entry
will be cleared and the memory used by the extra information will be released.
假设你有一些强引用的对象,并且他们存在一些额外的信息。我们将这些object当做WeakHashMap的key值,那些额外的信息当做value。
只要我们保持者对于这些对象的强引用,那么我们就可以通过这个weakHashMap来获取关于该对象的额外信息。而一旦我们释放了该对象
(放弃该对象的引用),这个对象相应的额外信息就会被清理
where you might keep track of what various threads in your system are doing; when the thread dies, the entry will be
removed silently from your map, and you won‘t keep the Thread from being garbage collected if you‘re the last reference
to it. You can then iterate over the entries in that map to find out what metadata you have about active threads in your system.
WeakHashMap<Thread, SomeMetaData>
当你需要跟踪在你系统中的各个线程正在干嘛时。当线程死亡时,这个entity就会悄无声息地从map中移除。当然你不能持有这些线程的强引用。
我们这样一来就可以通过遍历这个map来看一看那些线程在我们的系统中仍然活跃,也可以查看他对应的那些额外信息。
不要再value中保存对key的引用。
标签:style blog http color io os 使用 ar java
原文地址:http://www.cnblogs.com/maxmys/p/3999104.html