Java:使用jlibs保证垃圾收集

Java:使用jlibs保证垃圾收集,java,garbage-collection,Java,Garbage Collection,来自jlibs的以下代码片段保证GC完成垃圾收集 因为它也使用System.gc(),我不明白他们如何保证它会100%的发生 以下是片段: /** * This method guarantees that garbage collection is * done unlike <code>{@link System#gc()}</code> */ public static void gc(){ Object obj

来自jlibs的以下代码片段保证GC完成垃圾收集

因为它也使用System.gc(),我不明白他们如何保证它会100%的发生

以下是片段:

/**
     * This method guarantees that garbage collection is
     * done unlike <code>{@link System#gc()}</code>
     */
    public static void gc(){
        Object obj = new Object();
        WeakReference ref = new WeakReference<Object>(obj);
        obj = null;
        while(ref.get()!=null)
            System.gc();
    }

从我所能看到的,它应该像他们一样工作

1) 创建一个对象 2) 获取一个“弱”引用 3) null对它的引用,以便将其标记为垃圾回收
4) 然后等待while循环,直到它实际上消失为止,它与Garbae集合的强参考弱参考相关

强引用是一种普通的Java引用,您每天都使用这种引用

如果通过强引用链(强可访问)可以访问对象,则该对象不符合垃圾收集的条件。由于您不希望垃圾收集器破坏正在处理的对象,这通常正是您想要的

简单地说,弱引用是指不足以强制对象保留在内存中的引用。弱引用允许您利用垃圾收集器确定可达性的能力

pointed类中的gc()方法处理这个概念

     /**
       * This method guarantees that garbage collection is
       * done unlike <code>{@link System#gc()}</code>
       */

       public static void gc(){
            Object obj = new Object();
            WeakReference ref = new WeakReference<Object>(obj);
            obj = null;
            while(ref.get()!=null)
                System.gc();
        }
一旦WeakReference开始返回null,它指向的对象就变成了垃圾,WeakReference对象几乎毫无用处。这通常意味着需要进行某种清理

这就是为什么他们保证它会100%的发生

对System.gc()的单个调用不能保证重新声明所有符合垃圾收集条件的对象。看

在这种情况下,垃圾收集会运行多次,直到弱对象ref返回null。我怀疑这种方法的有效性。将有许多其他对象可能被垃圾收集。对我来说,它(jlib)没有任何东西可以学习

例如,库中2009年编写的代码。(节选)


为什么在调用shutdown时需要gc?所引用的库纯粹是垃圾。

是否要确保所有终结器都已运行?
/**
     * This method guarantees that garbage colleciton is
     * done after JVM shutdown is initialized
     */
    public static void gcOnExit(){
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run(){
                gc();
            }
        });
    }