调用System.gc没有立即执行的解决方法
2016-08-31 16:49
288 查看
查看源码
当我们调用System.gc()的时候,其实并不会马上进行垃圾回收,甚至不一定会执行垃圾回收,查看系统源码可以看到/** * Indicates to the VM that it would be a good time to run the * garbage collector. Note that this is a hint only. There is no guarantee * that the garbage collector will actually be run. */ public static void gc() { boolean shouldRunGC; synchronized(lock) { shouldRunGC = justRanFinalization; if (shouldRunGC) { justRanFinalization = false; } else { runGC = true; } } if (shouldRunGC) { Runtime.getRuntime().gc(); } }
也就是
justRanFinalization=true的时候才会执行
查找发现当调用runFinalization()的时候
justRanFinalization变为
true
下面是runFinalization()的源码
/** * Provides a hint to the VM that it would be useful to attempt * to perform any outstanding object finalization. */ public static void runFinalization() { boolean shouldRunGC; synchronized(lock) { shouldRunGC = runGC; runGC = false; } if (shouldRunGC) { Runtime.getRuntime().gc(); } Runtime.getRuntime().runFinalization(); synchronized(lock) { justRanFinalization = true; } }
其实当我们直接调用
System.gc()只会把这次gc请求记录下来,等到
runFinalization=true的时候才会先去执行GC,
runFinalization=true之后会在允许一次system.gc()。之后在call System.gc()还会重复上面的行为。
所以System.gc()要跟System.runFinalization()一起搭配使用才好。
查看
ZygoteInit.java里面 gc()和runFinalizationSync()是配合使用的,这样才有效果
static void gcAndFinalize() { final VMRuntime runtime = VMRuntime.getRuntime(); /* runFinalizationSync() lets finalizers be called in Zygote, * which doesn't have a HeapWorker thread. */ System.gc(); runtime.runFinalizationSync(); System.gc(); }
解决方案
由此可见,当我们需要调用的System.gc()的时候 要这样才会执行
System.gc(); runtime.runFinalizationSync(); System.gc();
不过个人建议不到万不得已不要调用,因为jvm有自己的gc策略,根本不需要我们来手动
转载请注明出处:http://www.weyye.me/detail/System-gc-not-called/
相关文章推荐
- uva1262 Password【解法二】
- Concurrent Requests - Parameters
- 欢迎使用CSDN-markdown编辑器
- How to restart USB device(如何重启USB设备)
- Xcode常用快捷键
- Linux下如何强制中断一个程序的执行?
- Js中获取超链接里面传递的参数值
- Dubbo简介及实例
- ndk系列——使用新版Android Studio创建ndk项目
- 我的第一个网站(一)
- 深度剖析:如何实现一个 Virtual DOM 算法
- iOS-收集的不常用却实用的小方法和技巧
- 曲线平滑-B样条曲线
- Linux下网络流量实时监控工具大全
- 各种数据库连接URL关键代码
- LeetCode candy
- 经典面试题之字符串的全排列
- 解决win10系统flash player无法播放,升级
- Android之NestedScrollView 嵌套 RecyclerView 滑动冲突的问题
- PCI/PCIe那些事(3)-- Configuration Space Type 0/1