问题描述:

In Java, when we close a resource like a Connection, a FileInputStream, a FileOutputStream, how is it different than setting these object instances to null? i.e in both scenarios, these objects are eligible for garbage collection. So what is the purpose of providing the close method with these classes?

网友答案:

The close method of IO classes is usually there to execute cleanup tasks, e.g. closing file handlers, flushing and closing sockets. These cleanup tasks are not related purely to allocation and GC itself cannot handle them.

Further, setting a reference to null to explicitly declare that the object will no longer be used is not a recommended coding practice. The GC will automatically handle the cases when the object is no longer accessible. Explicit null setting will only clutter your source code.

相关阅读:
Top