Reputation: 3419
I have always learned to always close a stream when I finish using it. Java 7 gives you a new option to do this (namely: try-with-resources), and it's all fine, except that when I close the OutputStream
of a socket, the socket gets closed aswell. This is counter-productive, because I am using sockets in a streaming application.
So if I execute the code below, I understand the ObjectOutputStream
gets closed after the try-block, and the socket's OutputStream
gets closed too, which finally leads to closing my Socket.
try(ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream())) {
oos.writeObject(new MyDTO(data));
}
I could of course change my code to look like below, but everyone has always told me I should close my Streams when I finish using them. And this is just one method, but I have multiple other methods which also use the OutputStream
and ObjectOutputStream
to send data to my client(s).
try {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream())
oos.writeObject(new MyDTO(data));
}
Do I have to expect other errors and misbehaviors as a result of not closing the ObjectOutputStream
? I think it's nice that the socket is closed, when you have bursty-traffic applications, but it is kind-of weird when you're doing a streaming application.
What's the best practice? Teach me please.
Upvotes: 0
Views: 338
Reputation: 310884
The question doesn't really make sense. You can't in practice create multiple ObjectOutputStreams
over the same socket (and even if you know how to do it there is no advantage), so there is no reason to be using try-with-resources with the ObjectOutputStream
in the first place. It should be created along with the socket, almost certainly stored as an instance member somewhere, and closed when you're finished with the connection.
Upvotes: 1
Reputation: 73538
Obviously if you still need the resources, you won't close them. The idea is to close them after you're done with them. If you're creating a chat software, you'd keep the connection open and the resources in use. However if you were to create some sort of poor man's FTP software, you might want to close the connection after the file has been transferred.
The try-with-resources
is to make it easier to write code that is guaranteed to release its resources, which is often useful when dealing with streams, database connections and other such things. You don't have to use it everywhere, especially when it makes your work harder.
Upvotes: 1