Darragh.McL
Darragh.McL

Reputation: 117

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 e.g.

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.

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?

Upvotes: 2

Views: 873

Answers (2)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44449

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.

However to answer the follow up questions:

  1. Yes, I believe the try-with-resources statement is evaluated in order of occurence.
  2. In case it isn't, you can always just add your own finally block at the end to explicitly close it yourself.

Note that the JLS $14.20.3 says this:

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.

Upvotes: 3

Paul John
Paul John

Reputation: 1661

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. i.e mStream will be created first, followed by mObjectStream.

Also, they will be closed in the reverse order. Latest one will be closed first followed by older ones.

Upvotes: 5

Related Questions