I have simple TCP server which prints the message sent by client. I'm trying to modify it to use try-with-resource feature. Is using nested try-with-resource statement in my example correct?
public static void main(String args[]) throws IOException {
String receivedMessage;
try (ServerSocket serverSocket = new ServerSocket(777)) {
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected");
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
while ((receivedMessage = in.readLine()) != null) {
System.out.println(receivedMessage);
}
System.out.println("Client disconnected");
}
}
}
}
}
Nesting try-catch blocks severely impacts the readability of source code because it makes it to difficult to understand which block will catch which exception.
The try-with-resources statement automatically closes all the resources at the end of the statement. A resource is an object to be closed at the end of the program. As seen from the above syntax, we declare the try-with-resources statement by, declaring and instantiating the resource within the try clause.
The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement.
You can use catch and finally blocks with try-with-resources statement just like an ordinary try statement.
Yes, your example is correct.
A try-with-resources try
block can stand alone because it has an implicit finally
block; whereas a traditional try
block is required to be followed by a catch
block and/or a finally
block.
Thus your example code is equivalent to the following (besides the resource variables being visible outside the scope of their respective try blocks):
final ServerSocket serverSocket = new ServerSocket(777);
try {
while (true) {
Socket socket = serverSocket.accept();
System.out.println("Client connected");
final BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
try {
while ((receivedMessage = in.readLine()) != null) {
System.out.println(receivedMessage);
}
System.out.println("Client disconnected");
} finally {
in.close();
}
}
} finally {
serverSocket.close();
}
I would have recommended you put both resources inside the same try block, except in your case that doesn't work because it's necessary to call accept()
on the serverSocket before asking for its inputStream()
.
However, there's still an appropriate opportunity in your code example to put multiple resources in your second try-with-resources:
try (Reader stream = new InputStreamReader(socket.getInputStream());
BufferedReader in = new BufferedReader(stream)) {
// do stuff, still preferring to use 'in' here rather than 'stream'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With