How to force garbage collection in Java?

后端 未结 22 1563
离开以前
离开以前 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

    There is some indirect way for forcing garbage collector. You just need to fill heap with temporary objects until the point when garbage collector will execute. I've made class which forces garbage collector in this way:

    class GarbageCollectorManager {
    
        private static boolean collectionWasForced;
        private static int refCounter = 0;
    
        public GarbageCollectorManager() {
            refCounter++;
        }
    
        @Override
        protected void finalize() {
            try {
                collectionWasForced = true;
                refCounter--;
                super.finalize();   
            } catch (Throwable ex) {
                Logger.getLogger(GarbageCollectorManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    
        public int forceGarbageCollection() {
            final int TEMPORARY_ARRAY_SIZE_FOR_GC = 200_000;
            int iterationsUntilCollected = 0;
            collectionWasForced = false;
    
            if (refCounter < 2) 
                new GarbageCollectorManager();
    
            while (!collectionWasForced) {
                iterationsUntilCollected++;
                int[] arr = new int[TEMPORARY_ARRAY_SIZE_FOR_GC];
                arr = null;
            }
    
            return iterationsUntilCollected;
        }
    
    }
    

    Usage:

    GarbageCollectorManager manager = new GarbageCollectorManager();
    int iterationsUntilGcExecuted = manager.forceGarbageCollection();
    

    I don't know how much this method is useful, because it fills heap constantly, but if you have mission critical application which MUST force GC - when this may be the Java portable way to force GC.

提交回复
热议问题