What exactly takes place behind the scenes when you call System.gc()?

寵の児 提交于 2019-12-24 08:28:22

问题


Calling System.gc() requests that garbage collection takes place, and isn't guaranteed. The part about it not being guaranteed is interesting to me: can someone explain the exact process that takes place when you make this call?


回答1:


There are no guarantees that a garbage collection will take place, because there are no guarantees that the JVM supports garbage collection (I don't believe it's mentioned in the JLS at all, certainly not in the index).

However, I think this belief that "it's not guaranteed" is a little misplaced. From the Sun API docs:

When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

OK, so maybe it's not guaranteed, but this indicates to me that a normal JVM will actually start a GC cycle when you call this method. Perhaps some JVMs won't, and perhaps some future garbage collector won't, but for now, it does what's advertised.

Of course, that said, there's almost never a reason for application code to call this method. The JVM will collect the garbage when it needs to do so.




回答2:


The exact process is JVM specific, and is actually an area where a lot of research is taking place. This is possible because the specification is so vague on what actually should happen.

Originally Java had a "stop everything and look at every object to see which ones are still alive". This was 1) slow and 2) stopped everything while this happened.

Today, Sun-based JVM's have several pools of objects as most objects do not live long, so by keeping the separate pools much work can be avoided.

Suns documentation on how to tweak the gc in java 5 is quite instructive on what goes on:

http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html




回答3:


The exact process depends on the version and vendor of the JVM.

There are different algorithms - mark and sweep, generational, etc. Usually they run in a parallel threads.

A JVM can have the call to System.gc() disabled, so that's one good reason is isn't guaranteed. IBM's Java theory and practice: Garbage collection and performance talks more about this, and explains why what seems obvious for helping out the GC can actually hurt performance. It also explains many of the algorithms that are used for implementing GC's.

Sun also has described a variety of their GC implementations in Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning.



来源:https://stackoverflow.com/questions/1083935/what-exactly-takes-place-behind-the-scenes-when-you-call-system-gc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!