Unsafe真的没有GC吗?

大纲007
  • 157

如何测试实例化的对象有没有GC ?
unsafe.allocateInstance(KlassA.class)

回复
阅读 378
1 个回答
        try {
            Field theInternalUnsafe1 = Unsafe.class.getDeclaredField("theInternalUnsafe");
            theInternalUnsafe1.setAccessible(true);
            jdk.internal.misc.Unsafe theInternalUnsafe = (jdk.internal.misc.Unsafe) theInternalUnsafe1.get(null);

            Integer e = (Integer)theInternalUnsafe.allocateInstance(Integer.class);
            WeakReference<Integer> reference=new WeakReference<Integer>(e);
            e = null;
            System.out.println(reference.get());
            System.gc();//通知GVM回收资源
            System.out.println(reference.get());

        } catch (Exception e) {
            e.printStackTrace();
        }
宣传栏