简体   繁体   English

如何清除资源泄漏?

[英]How to Clear Resource Leaks?

I have a Java code that I have been testing, the code uses the scanner class without closing it.我有一个我一直在测试的 Java 代码,该代码使用扫描仪 class 而不关闭它。 I know that this causes memory leaks and that the memory that was occupied by the scanner resources during the code execution is still occupied by the scanner resources even after the code finishes its' execution.我知道这会导致 memory 泄漏,并且在代码执行期间被扫描器资源占用的 memory 即使在代码完成执行后仍被扫描器资源占用。 I know closing the scanner helps prevent this issue, but for the times the code has been tested without closing the scanner class, does restarting the computer free up the memory that was taken by the scanner class when it wasn't closed after the code's execution?我知道关闭扫描仪有助于防止这个问题,但是在没有关闭扫描仪 class 的情况下测试代码的时候,重新启动计算机是否会释放 memory 由扫描仪获取的 ZA2F2ED4F8EBC2CBB4C21A29DC40AB61Z 在执行代码后关闭?

You do not need to restart the whole computer.您不需要重新启动整个计算机。 Whenever your Java application ends, all occupied memory is given back to the operating system.每当您的 Java 应用程序结束时,所有占用的 memory 都会返回给操作系统。

To expand on Stephans answer:要扩展斯蒂芬斯的答案:
So from my understanding, when a Java Program (Application or whatever) is started, a Java Virtual Machine (JVM) is instantiated.因此,据我了解,当启动 Java 程序(应用程序或其他)时,会实例化 Java 虚拟机(JVM)。 This is what will provide and consume all the memory etc. that your program requires.这将提供和使用您的程序所需的所有 memory 等。 When the Scanner class is scanning files, it will ask the JVM for file handles (these are the things that get handed back when the Scanner is closed), these may run out - which is why you need to close your Scanners (or use the Java 8+ try with resources).当扫描仪 class 正在扫描文件时,它会向 JVM 询问文件句柄(这些是在扫描仪关闭时返回的东西),这些可能会用完 - 这就是为什么您需要关闭扫描仪(或使用Java 8+ 尝试资源)。
It is the JVM which needs to be restarted, not the computer running the JVM.需要重新启动的是 JVM,而不是运行 JVM 的计算机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM