The try-with-resource statement will only close resources declared in the parentheses between the inside the try.
try ( /*anything declared here will be closed*/) {
}
The when the try ends, the try with resource will call close()
on any resource declared. This doesn't necessarily "destroy" an object like a destructor in C, but it is often used that way. The variable will also fall out of scope outside the try so it can be garbage collected.
IN your example stdIn
wraps System.in
so System.in
WILL BE CLOSED. However since it is still in scope after the try, it will not be garbage collected. (but you can't write to it anymore)
Try-with-resource is just "syntatic sugar" and will be compiled into something like this:
Socket echoSocket =null
PrintWriter out =null
BufferedReader in =null
BufferedReader stdIn =null
try{
echoSocket = new Socket(hostName, portNumber);
out =
new PrintWriter(echoSocket.getOutputStream(), true);
in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
stdIn =
new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
}finally{
if(stdIn !=null){
try{
stdIn.close()
}catch(Exception e){
//surpress exception if needed
}
}
if(in !=null){
try{
in.close()
}catch(Exception e){
//surpress exception
}
}
if(out !=null){
try{
out.close()
}catch(Exception e){
//surpress exception
}
}
if(echoSocket !=null){
try{
echoSocket.close()
}catch(Exception e){
//surpress exception
}
}
}
Notice that the resources are closed in reverse order to solve the nesting issue. If something threw an exception in the try block AND something else threw an exception in the finally block, then the "surpress exception" gets added to the original Exception object which can be retrieve via the new Throwable.getSuppressed()
method. This is so the stacktrace correctly shows the original exception that was thrown inside the try.
for more information about try-with-resource see Oracle's tutorial: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html