英文:
How to Clear Resource Leaks?
问题
我有一个Java代码,我一直在测试,该代码使用了Scanner类而没有关闭它。我知道这会导致内存泄漏,而在代码执行期间由Scanner资源占用的内存仍然会在代码执行完毕后被Scanner资源占用。我知道关闭Scanner有助于防止这个问题,但是对于那些在没有关闭Scanner类的情况下进行测试的代码,重新启动计算机是否会释放在代码执行后未关闭Scanner类时被占用的内存?
英文:
I have a Java code that I have been testing, the code uses the scanner class without closing it. 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. 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?
答案1
得分: 1
你不需要重新启动整个计算机。每当您的Java应用程序结束时,所有占用的内存都会归还给操作系统。
英文:
You do not need to restart the whole computer. Whenever your Java application ends, all occupied memory is given back to the operating system.
答案2
得分: 0
根据Stephans的回答进行详细解释:当启动Java程序(应用程序或其他)时,会实例化一个Java虚拟机(JVM)。这是提供和消耗程序所需的所有内存等资源的组件。当Scanner类扫描文件时,它会向JVM请求文件句柄(这些是在关闭Scanner时返回的东西),这些句柄可能会用尽,这就是为什么需要关闭Scanner(或使用Java 8+的资源尝试)的原因。需要重新启动的是JVM,而不是运行JVM的计算机。
英文:
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. This is what will provide and consume all the memory etc. that your program requires. 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).
It is the JVM which needs to be restarted, not the computer running the JVM.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论