简体   繁体   English

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

[英]Execution order of try-with-resource resource creation

I have a try-with-resource block that creates a new instance of an ObjectInputStream from a Blob object eg 我有一个try-with-resource块,它从Blob对象创建ObjectInputStream的新实例,例如

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

However, if an exception is thrown at .getBinaryStream() the mObjectStream object could potentially be left unreleased which is a concern with my application. 但是,如果在.getBinaryStream()中抛出异常,则mObjectStream对象可能会被释放 ,这与我的应用程序有关。

I have considered separating this as follows 我考虑将其分开如下

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

}

Would this cause issues if mObjectStream is created first or will mStream always be created first in this case? 想,如果mObjectStream首先创建或将Mstream工具,总是在这种情况下,第一次创建这个事业的问题?

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

When you list and open multiple resources, they will be created in the order in which they are declared. 当您列出并打开多个资源时,将按照声明它们的顺序创建它们。 ie mStream will be created first, followed by mObjectStream. 即首先创建mStream,然后创建mObjectStream。

Also, they will be closed in the reverse order. 此外,它们将以相反的顺序关闭。 Latest one will be closed first followed by older ones. 最新的一个将先关闭,然后是旧的。

This shouldn't be a problem: if getBinaryStream() throws an exception then mObjectStream won't be created in the first place since the constructor is only called after getBinaryStream() returns. 这应该不成问题:如果getBinaryStream()引发异常,则不会首先创建mObjectStream ,因为仅在getBinaryStream()返回之后才调用构造函数。

However to answer the follow up questions: 但是要回答后续问题:

  1. Yes, I believe the try-with-resources statement is evaluated in order of occurence. 是的,我相信try-with-resources语句是按照发生的顺序进行评估的。
  2. In case it isn't, you can always just add your own finally block at the end to explicitly close it yourself. 如果不是,您可以随时添加自己的finally块,以便自己明确关闭它。

Note that the JLS $14.20.3 says this: 请注意, JLS $ 14.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 . 如果资源无法初始化 (即,其初始化程序表达式抛出异常), 则会关闭try-with-resources语句到目前为止初始化的所有资源 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. 如果所有资源都成功初始化,则try块将正常执行,然后关闭try-with-resources语句的所有非空资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM