java中的资源是什么?为什么我们必须在使用它之后关闭它? [英] What is a resource in java?why we have to close it after it is used?

查看:547
本文介绍了java中的资源是什么?为什么我们必须在使用它之后关闭它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中resource这个词的含义是什么?
为什么我们必须在使用后关闭它,即使垃圾收集器运行在jvm中?
为什么我们必须在finally块中编写资源清理代码?

解决方案

资源是有限的ammount如数据库连接和文件描述符。 GC释放内存,但仍需释放资源,如数据库连接,打开的文件等,以允许其他线程使用它们。



方式,最好在完成使用后立即释放资源,而不是在 finalize 方法中,这可能需要很长时间才能被GC调用。

What is the meaning of the word "resource" in java? Why we have to close it after usage,even though garbage collector runs in jvm ? Why we have to write resource cleanup code in finally block?

解决方案

A resource is something that has a limited ammount, such as DB connections and file descriptors. The GC frees memory, but you still have to release resources such as DB connections, open files, etc..., to allow other threads to use them.

By the way, it's better to free the resources immediately after you finish using them, and not just in the finalize method, which might take a long time until it is called by the GC.

这篇关于java中的资源是什么?为什么我们必须在使用它之后关闭它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆