[英]Why is WeakReferenced object not removed by WeakHashMap
I recently tried to understand java.util.WeakHashMap. 我最近尝试了解java.util.WeakHashMap。
But when I use WeakReference to wrap a String, the WeakHash isn't finalizing the Entry. 但是,当我使用WeakReference来包装字符串时,WeakHash不会最终确定Entry。
Also note that I am clearing the WeakReference in the main thread before it is been referred inside the thread method. 另请注意,在线程方法中引用WeakReference之前,我先清除了该线程中的WeakReference。
When executed, while loop isn't breaking at all! 当执行时,while循环根本不会中断!
public class WeakHashMapTotorial
{
private static Map<String, String> map;
public static void main(String args[])
{
WeakReference<String> s = new WeakReference<String>("Maine");
map = new WeakHashMap<>();
map.put(s.get(), "Augusta");
Runnable runner = new Runnable()
{
public void run()
{
while (map.containsKey("Maine"))
{
try
{
Thread.sleep(1000);
} catch (InterruptedException ignored)
{}
System.out.println("Thread waiting");
System.gc();
}
}
};
Thread t = new Thread(runner);
t.start();
System.out.println("Main waiting");
try
{
t.join();
} catch (InterruptedException ignored)
{}
s.clear();
}
}
Wrapping a WeakReference
around a String constant will not work. 将WeakReference
封装在String常量周围将不起作用。 String constants are interned, which means the reference will never go away. 字符串常量是内在的,这意味着引用永远不会消失。 Additionally, your code keeps a reference to the same constant in your run method, further guaranteeing a strong reference remains. 另外,您的代码在run方法中保留对相同常量的引用,从而进一步确保了强大的引用保留。
The Strings that you are using are being held by the pool of interned strings, try the following: 您正在使用的字符串由实习字符串池保存,请尝试以下操作:
WeakReference<String> s = new WeakReference<String>(new String("Maine"));
map = new WeakHashMap<>();
map.put(s.get(), "Augusta");
This interning effect is described in the Java Language Spec Java语言规范中描述了这种嵌入效果
Moreover, a string literal always refers to the same instance of class String. 而且,字符串文字总是指代String类的相同实例。 This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern. 这是因为使用方法String.intern,对字符串文字(或更常见的是作为常量表达式值的字符串(第15.28节))进行了“插入”,以便共享唯一的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.