Java - 字符串的WeakReference

时间:2016-03-14 11:08:34

标签: java garbage-collection weak-references

使用WeakReference时,似乎正常对象和行为上的行为字符串是不同的。

代码

WeakReferenceTest.java: junit test

import java.lang.ref.WeakReference;

import junit.framework.TestCase;

import org.junit.Test;

public class WeakReferenceTest extends TestCase {
    @Test
    public void testWeakReference() throws InterruptedException {
        Person pone = new Person();
        WeakReference<Person> personRef = new WeakReference<Person>(pone);
        assertNotNull(personRef.get());

        pone = null; // clear reference,
        int i = 0;
        while (personRef.get() != null) {
            System.gc();
            i++;
            Thread.sleep(1000);
        }
        System.out.printf("The [%s] weak reference is removed after %d times System.gc()\n", "Person", i);
    }

    @Test
    public void testWeakReferenceOnString() throws InterruptedException {
        String name = "eric";
        WeakReference<String> strRef = new WeakReference<String>(name);
        assertNotNull(strRef.get());

        name = null; // clear reference,
        int i = 0, maxLoop = 5;
        while (strRef.get() != null) {
            System.gc();
            i++;
            if (i == maxLoop) {
                break;
            }
            Thread.sleep(1000);
        }
        if (strRef.get() == null) {
            System.out.printf("The [%s] weak reference is removed after %d times System.gc()\n", "String", i);
        } else {
            System.out.printf("The [%s] weak reference is still not removed after %d times System.gc(), quit it.\n", "String", i);
        }
    }

    private class Person {
    }
}

第三方罐子 - 通过maven:

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
    </dependency> 

执行结果:

  

System.xc()后1次删除[Person]弱引用   System.gc()5次后仍然没有删除[String]弱引用,退出它。

问题是:

  • 似乎WeakReference上的String在gc时被清除,是由于字符串文字的常量池吗?

0 个答案:

没有答案