How to force garbage collection in Java?

2018-12-31 03:23发布

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 to do GC. How can I force GC?

21条回答
泪湿衣
2楼-- · 2018-12-31 04:15

Using the Java™ Virtual Machine Tool Interface (JVM TI), the function

jvmtiError ForceGarbageCollection(jvmtiEnv* env)

will "Force the VM to perform a garbage collection." The JVM TI is part of the JavaTM Platform Debugger Architecture (JPDA).

查看更多
春风洒进眼中
3楼-- · 2018-12-31 04:15

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.

查看更多
梦醉为红颜
4楼-- · 2018-12-31 04:18

It would be better if you would describe the reason why you need garbage collection. If you are using SWT, you can dispose resources such as Image and Font to free memory. For instance:

Image img = new Image(Display.getDefault(), 16, 16);
img.dispose();

There are also tools to determine undisposed resources.

查看更多
栀子花@的思念
5楼-- · 2018-12-31 04:20

Use Runtime.getRuntime().gc() or use utility method System.gc()

查看更多
爱死公子算了
6楼-- · 2018-12-31 04:21

JVM specification doesn't say anything specific about garbage collection. Due to this, vendors are free to implement GC in their way.

So this vagueness causes uncertainty in garbage collection behavior. You should check your JVM details to know about the garbage collection approaches/algorithms. Also there are options to customize behavior as well.

查看更多
千与千寻千般痛.
7楼-- · 2018-12-31 04:21

(Sorry I can't add this as a comment as I don't have enough reputation points.)

I once interviewed at an image processing company for a Java job (even though I didn't have any/much java experience.)

Their tale of woe that was interesting to me, was their program would allocate a HUGE buffer for image. Once, they were done with the image and memory, they would deference it. Knowing that they really needed to recover the memory sooner than later, they tried to use an explicit call to Java gc() during a quiet time of the program. Unfortunately, gc() is merely a suggestion to the Java runtime and had no effect.

As I recall, they ended up having to recycle the memory themselves.

查看更多
登录 后发表回答