本文介绍了java中的字符串文字和垃圾收集器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更具体地说,我已经读过,在java 7中,字符串文字现在存储在堆的主要部分,所以它们是否有资格使用垃圾回收器?

 字符串a =z; 
a = null;

现在对象z被垃圾收集,或者仍然在字符串池中作为匿名对象?

解决方案

只有当所有包含这些文字的类都是GCed时,字符串文字才能被GCed,而这只会在ClassLoaders加载这些类是GCed。



示例:

  public interface I { 
String getString();
}

public class Test2 implements I {
String s =X;
@Override
public String getString(){
return s;
}
}

public class Test implements I {
String s =X;
@Override
public String getString(){
return s;



public class Test1 {

public static void main(String [] args)throws Exception {
ClassLoader cl = new URLClassLoader(new URL [] {new URL(file:d:/ test /)});
I i =(I)cl.loadClass(Test)。newInstance();
WeakReference w = new WeakReference(i.getString()); //向文字X的微弱引用
i = null;
cl = null;
System.out.println(w.get());
System.gc();
Thread.sleep(1000);
System.out.println(w.get());






$ b

编译这些类,将Test.class移动到d: / test,以便系统类加载器不能看到它,然后运行main。你会看到

  X 
null

这意味着X是GC ed

To be more specific I've read that in java 7 string literal are now stored in the main part of the heap so, do they become eligible for garbage collector?

String a ="z";
a = null;

Now does the object "z" get garbage collected,or still in the string pool as an anonymous object ?

解决方案

String literals can only be GCed when all classes contaning these literals are GCed which in turn can only happen if ClassLoaders which loaded these classes are GCed.

Example:

public interface I {
    String getString();
}

public class Test2 implements I {
    String s = "X";
    @Override
    public String getString() {
        return s;
    }
}

public class Test implements I {
    String s = "X";
    @Override
    public String getString() {
        return s;
    }
}

public class Test1 {

    public static void main(String[] args) throws Exception {
        ClassLoader cl = new URLClassLoader(new URL[] {new URL("file:d:/test/")});
        I i = (I)cl.loadClass("Test").newInstance();
        WeakReference w = new WeakReference(i.getString()); //weak ref to "X" literal
        i = null;
        cl = null;
        System.out.println(w.get());
        System.gc();
        Thread.sleep(1000);
        System.out.println(w.get());
    }
}

compile these classes, move Test.class to d:/test so that system class loader cannot see it, then run main. You will see

X
null

which means "X" was GC ed

这篇关于java中的字符串文字和垃圾收集器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:51