简体   繁体   中英

Do I need to close reader or will garbage collector close it when I overwrite the variable?

I'm reading binary files, since I can't serialize my class I decided to read and write data structures separately.

For example:

After I read the data on the 2nd line of code, do I need to close the reader or if I overwrite the variable with a new reader will the garbage collector take care of it automatically?

i = new ObjectInputStream(new FileInputStream(CONTACTSSAVE));
addAllContacts((HashSet<String>) i.readObject());
i = new ObjectInputStream(new FileInputStream(APIKEYSAVE));

When in doubt, always explicitly close AutoCloseable / Closeable resources like input streams, output streams, sockets, database connections, etc.

When you rely on the garbage collector to handle it for you, the file (or other resource) may remain open for a very long time (maybe even until Java exits). This means that you unnecessarily keep resources and memory open, which may impact performance, or it may hinder other applications (or other parts of your application), for example if they need exclusive access to overwrite the file.

This is even worse with output streams, because failure to close the stream may - for example - mean that not all changes have been written to disk, which may result in data loss if Java exits as finalizers are not guaranteed to run on exit, so the close may be abrupt without flushing buffers instead of graceful.

If you use try-with-resources to do this, you even have the added benefit that you don't accidentally leak the resource, for example, your code would then become:

try (ObjectInputStream contacts = new ObjectInputStream(new FileInputStream(CONTACTSSAVE))) {
   addAllContacts((HashSet<String>) contacts.readObject());
}

try (ObjectInputStream apikey = new ObjectInputStream(new FileInputStream(APIKEYSAVE))) {
    // load things from apikey
}

The vm might close the stream that not used in finalize method. But it's still necessary to close the stream by yourself. It's hard to know when it would be closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM