How to force garbage collection in Java?

后端 未结 22 1564
离开以前
离开以前 2020-11-22 00:31

Is it possible to force garbage collection in Java, even if it is tricky to do? I know about System.gc(); and Runtime.gc(); but they only suggest t

22条回答
  •  面向向阳花
    2020-11-22 00:51

    The jlibs library has a good utility class for garbage collection. You can force garbage collection using a nifty little trick with WeakReference objects.

    RuntimeUtil.gc() from the jlibs:

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

    提交回复
    热议问题