调用System.gc没有立即执行的解决方法
来源:互联网 发布:兰州seo安安网站建设 编辑:程序博客网 时间:2024/06/06 21:02
查看源码
当我们调用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/
0 0
- 调用System.gc没有立即执行的解决方法
- 调用System.gc没有立即执行
- System.gc()调用
- System.gc()调用
- 自动执行函数/立即调用的函数表达式
- 【Android实战】----调用startActivityForResult()后,onActivityResult()立即执行的问题
- Ubuntu 14.04 没有system settings的解决方法
- 函数的立即执行
- setTimeout立即执行,没有延迟效果
- setTimeout立即执行,没有延迟效果
- setTimeout立即执行,没有延迟效果
- java 手动调用System.gc();
- 最简单的Btrace查询System.gc的调用
- Fragment中的onCreatView()没有立即调用
- performSelector 和 NSTimer没有执行的解决方法
- System.gc() 的特性
- 自执行or立即调用函数
- 调用startAcyivityForResult后立即执行onActivityResult
- 我的第一个网站(一)
- SQL 2005 创建表报错:类别不支持集合(或类别对象为远程对象)
- 欢迎使用CSDN-markdown编辑器
- uva1262 Password【解法二】
- java 调用.net DLL的方法
- 调用System.gc没有立即执行的解决方法
- TCP UDP 回顾
- mysql innodb只有 .frm .ibd 文件 如何恢复数据
- 【leetcode】389. Find the Difference
- win服务器设置开机自动登录
- Leetcode: Generate Parentheses
- tmux常用命令与快捷键
- C/C++ Volatile关键词深度剖析
- ruby on rails 使用text存储hash类型的数据 Use text filed to store the hash map