try-with-resource资源创建的执行顺序

Execution order of try-with-resource resource creation

我有一个 try-with-resource 块,它从 Blob 对象创建 ObjectInputStream 的新实例,例如

try(ObjectInputStream mObjectStream = new ObjectInputStream(mblob.getBinaryStream()))
{
...
}

但是,如果在 .getBinaryStream() 处抛出异常,则 mObjectStream 对象可能未被释放,这是与我的申请。

我考虑过将其拆分如下

try(InputStream mStream = mblob.getBinaryStream(); ObjectInputStream mObjectStream = new ObjectInputStream(mStream){
...

}

如果首先创建 mObjectStream 是否会导致问题,或者在这种情况下总是首先创建 mStream

try(InputStream mStream = mblob.getBinaryStream();
 ObjectInputStream mObjectStream = new ObjectInputStream(mStream))

当您列出并打开多个资源时,它们将按照声明的顺序创建。即首先创建 mStream,然后是 mObjectStream。

此外,它们将以相反的顺序关闭。最新的先关,老的再关。

这应该不是问题:如果 getBinaryStream() 抛出异常,那么 mObjectStream 不会首先创建,因为构造函数仅在 getBinaryStream() 之后调用 returns.

但是要回答后续问题:

  1. 是的,我相信 try-with-resources 语句是按出现顺序计算的。
  2. 如果不是,您可以随时在末尾添加自己的 finally 块以自行明确关闭它。

请注意 JLS .20.3 是这样说的:

Resources are initialized in left-to-right order. If a resource fails to initialize (that is, its initializer expression throws an exception), then all resources initialized so far by the try-with-resources statement are closed. If all resources initialize successfully, the try block executes as normal and then all non-null resources of the try-with-resources statement are closed.