如果未手动关闭流,它何时关闭? [英] When does a stream close if its not closed manually?

查看:145
本文介绍了如果未手动关闭流,它何时关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果一个流没有手动关闭,它什么时候会关闭。我的意思是,如果它的参考范围不再是,那么流将被关闭吗?

I would like to know when does a stream close if its not closed manually. By this I mean, will the stream be closed if the scope of its reference is no more?

考虑以下示例场景。

Class A{
 InputStream in;
 OutputStream out;
 A(){
  // Initialize and create the streams.
 }
 ...
}
Class B{
 public void myMethod(){
 A a = new A();
 System.out.println("End of my method.")
 }
...
}

这里,一旦我完成了流,我退出 myMethod()但是程序又反过来了进程,不会终止并继续进行其他操作。

Here, once I am done with the stream, I am exiting myMethod() but the program which in turn the process, is not terminated and goes on with other operations.

我没有关闭流。一旦A类参考范围结束,它会自动关闭吗? (即当 myMethod()结束时)? GC会照顾到这个吗?此外,我读到,一旦进程结束,流将被关闭,系统将释放为其他进程保留的所有资源。我们如何检查流是否开放?是否有来自Java的任何linux命令或选项来检查?

I did not close the streams. Will it be closed automatically once the scope of the reference to class A ends? (ie. When myMethod() ends)? Does GC takes care of that? Also, I read that the streams will be closed once the process ends and the system releases all the resources held for it for other processes. How can we check whether the stream is open or not? Are there any linux commands or options from Java to check that?

感谢任何帮助!

推荐答案

我不认为JVM规范对此做出了任何保证。你真的应该最后关闭这些资源。

I don't think that the JVM spec makes any guarantee about that. You really are supposed to finally close these resources.

当流程结束时,操作系统将释放所有资源与之关联(包括内存,文件句柄和网络套接字)。

When the process ends, the operating system will release all resources associated to it (including memory, file handles, and network sockets).

有一些操作系统可以检查打开的文件和流,例如 lsof

There are OS facilities to check about open files and streams, such as lsof.

这篇关于如果未手动关闭流,它何时关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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