I know that the resource you pass with a try, will be closed automatically if the resource has AutoCloseable implemented. So far so good. But what do I do when i have several resources that I want automatically closed. Example with sockets;
try (Socket socket = new Socket()) {
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
}
So I know the socket will be closed properly, because it's passed as a parameter in the try, but how should the input and output be closed properly?
Try with resources can be used with multiple resources by declaring them all in the parenthesis. See the documentation
Relevant code excerpt from the linked documentation:
If your objects don't implement
AutoClosable
(DataInputStream
does), or must be declared before the try-with-resources, then the appropriate place to close them is in afinally
block, also mentioned in the linked documentation.In addition to the above answers, This is the improvement added in Java 9.
Java 9 try-with-resources makes an improved way of writing code. Now you can declare the variable outside the try block and use them inside try block directly.because of this you will get following benefits.
try-with-resource can we write like this in Java 9.
}
For the better understanding of the list of above define use cases please find some Java 7 code.
Example 1:
}
Example 2:
Don't worry, things will "just work". From Socket's documentation:
I understand your concern about not explicitly calling
close()
on the input and output objects and in fact it's generally better to ensure all resources are automatically managed by thetry-with-resources
block, like this:This would have the effect that the socket object would be "closed multiple times", but that should not do any harm (this is one of the reasons why it's generally advised that all implementations of
close()
be made idempotent).Answers above are great but there are some cases when try-with-resources doesn't help.
Take a look at this code example:
In this example u can't just use try-with-resources block cause writer has to flush the output buffer to the underlying character stream so placing writer into try-with-resources block won't do the trick and method will return empty array.