I'm working on a program using JSch to connect to a remote unix server. I also am connecting to a Hive database with jdbc and a distributed filesystem with Apache Hadoop HDFS API. I have been casually including the close() methods when I see they're available but there's growing frustration about trying to close the channels/connections when using a try/catch/finally block.
What is the actual consequence to leaving a stream, channel, or connection open? Does it affect the remote machine in a negative way? Do all streams automatically close when the program ends?
What is the actual consequence to leaving a stream, channel, or connection open?
At minimum it consumes resources until those endpoints are closed, which may or may not happen if they should be garbage collected. That may constitute a resource leak. In extreme cases, the program could exhaust the resources available to it (e.g. number of simultaneously open files).
Additionally, for output, data you have written to such sinks may remain buffered internally instead of actually being pushed out to the intended destination.
Does it affect the remote machine in a negative way?
Generally, any kind of persistent connection to a remote service engages system resources on the remote side. Those resources will normally be freed when the connection is cleanly closed. If it is not cleanly closed, then those resources may remain committed to the connection for an indeterminate time; details depend on the nature and configuration of the services involved.
Do all streams automatically close when the program ends?
In a low-level sense, yes. And for connection-oriented network streams, this will normally cause a network-layer closure to be performed that the remote side will see. However, if there is any relevant sense of an application-layer closure, you cannot expect that to be performed. What effect that might have on the remote system depends, again, on the nature and configuration of the services involved. Additionally, if you have buffered output pending, it might not be written before the underlying system resource is closed.
Overall, however, when you say
there's growing frustration about trying to close the channels/connections when using a try/catch/finally block
, I have little sympathy. The pattern is consistent and fairly easy to understand and implement. That you perceive it as tedious -- which perhaps it is -- does not give you license to skip managing resources properly. A great deal of the practice of programming is fairly humdrum. Good programmers handle all that, consistently and well. It's part of the job.
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