开发者

Does periodic garbage collection help JVM performance?

开发者 https://www.devze.com 2023-02-14 03:44 出处:网络
I just encountered the following code (slightly simplified): /* periodically requests garbagecollect to improve memory usage and

I just encountered the following code (slightly simplified):

/* periodically requests garbagecollect to improve memory usage and 
   garbage collect performance under most JVMs */
static class GCThread implements Runnable {
    public void run() {
        while(true) {
            try {
              Thread.sleep(300000);
            } catch (InterruptedException e) {}
            System.gc();           
        }
    }
}

Thread gcThread = new Thread(new GCThread());
gcThread.setDaemon(true);
gcThread.start();

I respect the author of the code, but no longer has easy access to ask 开发者_运维问答him to defend his assertion in the comment on top.

Is this true? It very much goes against my intuition that this little hack should improve anything. I would expect the JVM to be much better equipped to decide when to perform a collection.

The code is running in a web-application running inside a IBM WebSphere on Z/OS.


It depends.

  1. The JVM can completely ignore System.gc() so this code could do absolutely nothing.

  2. Secondly, a GC has a cost impact. If your program wouldn't otherwise have done a GC (say, it doesn't generate much garbage, or it has a huge heap and never needs to GC) then this code will be added overhead.

  3. If the program would normally run with just minor GCs and this code causes a major GC, you will have a negative impact.

All in all, this kind of optimisation makes absolutely no sense whatsoever unless you have concrete evidence that it provides benefit and you would need to re-evaluate that evidence every time the program materially changed.


I also share your assumption. If this is really an optimization, it would have found its way in the JVM. Calling the garbage collector should be avoided - it can even have negative effect (because you are "disturbing" the JVM)

JVMs will probably have a setting for gc interval. See here for Sun's. And Hardcoding the value is rather questionable for anything, especially for garbage collection.


Maybe it could be a good thing if your application could time the calls so that GC would occur at times when the application has nothing useful to do, so the memory is clean whenever the next load peak comes. But this is not what this loop does (it simply runs all 5 minutes), so I would advise against it.

But I invite you to test it - run the application with and without this loop for similar work volumes and measure which takes more time (and maybe total memory, if important). Repeat the test some times. Maybe we get some surprising insights.

0

精彩评论

暂无评论...
验证码 换一张
取 消