Java关于Resource leak: 'sc' is never closed的问题

Posted GGFWI

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java关于Resource leak: 'sc' is never closed的问题相关的知识,希望对你有一定的参考价值。

问题:编写Java时出现了Resource leak: \'sc\' is never closed的问题,也就是对象sc下面的波浪线产生的警告,鼠标放上去之后就可以知道详情。

原因Scanner sc = new Scanner(System.in)申明了名为s的数据输入扫描仪(Scanner),系统给它分配相应的内存空间,但是在程序结时却没有释放该内存,会造成资源浪费,因此出现警告。

ps:只是警告,程序依旧可以执行

解决方案:既然没有把它close,那就调用close()方法,关上它!在后面加上xxx.close()即可解决,XXX为定义的名字。

 

Resource leak: 'context' is never closed

from: http://stackoverflow.com/questions/14184059/spring-applicationcontext-resource-leak-context-is-never-closed

Since the app context is a ResourceLoader (i.e. I/O operations) it consumes resources that need to be freed at some point. It is also an extension of AbstractApplicationContext which implements Closable. Thus, it‘s got a close() method and can be used in a try-with-resources statement.

try (ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/userLibrary.xml")) {
  service = context.getBean(UserLibrary.class);
}

Whether you actually need to create this context is a different question (you linked to it), I‘m not gonna comment on that.

It‘s true that the context is closed implicitly when the application is stopped but that‘s not good enough. Eclipse is right, you need to take measures to close it manually for other cases in order to avoid classloader leaks.

以上是关于Java关于Resource leak: 'sc' is never closed的问题的主要内容,如果未能解决你的问题,请参考以下文章

Resource leak: 'context' is never closed

错误日志:Resource leak: 'xxx' is never closed(Scanner类的注意事项)

iOS 关于leak检测内存问题的使用

iOS 关于leak检测内存问题的使用

iOS 关于leak检测内存问题的使用

数据库内存泄漏——A SQLiteConnection object for database '/data/data/.../databases/....db' was leaked