如果流没有手动关闭,它什么时候关闭? [英] When does a stream close if its not closed manually?

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

问题描述

我想知道如果流没有手动关闭,它什么时候关闭.我的意思是,如果流的引用范围不再,是否会关闭流?

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天全站免登陆