调用System.gc没有立即执行
2016-09-01 08:12
260 查看
原文链接http://www.weyye.me/detail/System-gc-not-called/
查看源码
当我们调用System.gc()的时候,其实并不会马上进行垃圾回收,甚至不一定会执行垃圾回收,查看系统源码可以看到1234567891011121314151617181920 | /** * 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()的源码
12345678910111213141516171819 | /*** 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()是配合使用的,这样才有效果
12345678910 | 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()的时候 要这样才会执行
123 | System.gc();runtime.runFinalizationSync();System.gc(); |
相关文章推荐
- 调用System.gc没有立即执行的解决方法
- 在MySql里面查询有记录,但是调用程序执行就没有记录
- wince6.0电源管理之应用程序调用SetSystemPowerState的执行过程
- python调用os.system执行系统命令,中文输出显示乱码
- 项目实现过程中遇到的问题记录(一)------------使用AsyncTask时,doInBackground没有立即执行
- 通过回调函数 调用parent窗体 关闭子窗体 因为没有运行完需要的函数 回调关闭会出错 需要延时执行
- 什么时候在游戏中调用System.gc()?[javaME]
- 子进程中调用system命令执行openssl后,程序退出了,原因是SIGCHLD信号的处理
- Java 强制执行垃圾回收 System.gc()、System.runFinalization()
- 调用FileSystemObject.CopyFile发生没有权限的错误
- 如果使用没有提供选项值的 SqlDependency,必须先调用 SqlDependency.Start(),然后才能执行添加到 SqlDependency 实例中的命令
- Activity调用finish却不立即执行onDestory
- Control的Invoke和BeginInvoke 是相对于支线线程(因为一般在支线线程中调用,用来更新主线程ui)Invoke立即插入主线程中执行,而BeginInvoke 要等主线程结束才执行
- linux daemon中执行system调用方法
- Control的Invoke和BeginInvoke 是相对于支线线程(因为一般在支线线程中调用,用来更新主线程ui)Invoke立即插入主线程中执行,而BeginInvoke 要等主线程结束才执行
- wince6.0电源管理之应用程序调用SetSystemPowerState的执行过程
- 调用repaint()后为什么这个paintComponent()没有执行
- 通过system调用Am命令执行动作
- Android中调用finish()后不能立即执行onDestroy()的BUG
- Android中通过system调用Am命令执行动作