java 强制gc,Java:你如何使用JVMTI的ForceGargabeCollection强制GC?

I'm not looking for the usual "you can only hint the GC in Java using System.gc()" answers, this is not at all what this question is about.

My questions is not subjective and is based on a reality: GC can be forced in Java for a fact. A lot of programs that we use daily do it: IntelliJ IDEA, NetBeans, VisualVM.

They all can force GC to happen.

How is it done?

I take it they're all using JVMTI and more specifically the ForceGarbageCollection (notice the "Force") but how can I try it for myself?

Also note that this question is not about "why" I'd want to do this: the "why" may be "curiosity" or "we're writing a program similar to VisualVM", etc.

The question is really "how do you force a GC using JVMTI's ForceGarbageCollection"?

Does the JVM needs to be launched with any special parameters?

Is any JNI required? If so, what code exactly?

Does it only work on Sun VMs?

Any complete and compilable example would be most welcome.

解决方案

NetBeans, at least, uses System.gc(): http://hg.netbeans.org/main/annotate/9779f138a9c9/openide.actions/src/org/openide/actions/GarbageCollectAction.java (this is for the little button that shows current heap and lets you start GC). If you follow that link, you'll see that they explicitly run finalizers. If you have a few gig of disk space free, and want to investigate the code yourself, it's available via Mercurial: hg clone http://hg.netbeans.org/main/

As far as I can tell, the "System.gc() is just a hint" dogma originates in pedantic interpretation of the JLS and JVM Spec, which allow for Java implementations that don't have a garbage-collected heap. That, and an incomplete reading of the JavaDoc:

Calling the gc method suggests that

the Java Virtual Machine expend effort

toward recycling unused objects in

order to make the memory they

currently occupy available for quick

reuse. When control returns from the

method call, the Java Virtual Machine

has made a best effort to reclaim

space from all discarded objects.

Read the second sentence: "best effort to reclaim space" is a lot stronger than "hint."

That said, there's rarely a reason to call System.gc(). With apologies to Knuth:

We should forget about memory management, say about 97% of the time: explicit garbage collection is the root of all evil

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值