How is right to close and "destroy" an object in Java

Fagam32 :

I have a map

public class MyMap implements Map<String,String>

It does some stuff in DB and it should do one of the following destroy methods:

  1. If garbage collector destroyed myMap without close() than it should execute clear() method
  2. If object destroys after close(), than all data saves in DB

It should work like FileWriter. If you close stream - data saves, if you don't - you lose :(

What should I use? finalize() , simply implement Closeable or AutoCloseable or something different?

dan1st :

finalize() is deprecated since Java 9. It may not be called if the VM exits: if you call Runtime.runFinalizersOnExit(true) it will be executed (but there are other problems with this).

Instead you should implement AutoClosable.

This allows to automatically close the Map with a try-with-resources.

You can also close() the FileWriter in your close() method as FileWriter implements Closeable(even AutoCloseable) too.

If you want to, you can override the finalize() method as a backup in case the closing did not work correctly but take care of the performance problems and the following as my source states:

  • Always call super.finalize() in your finalize() method.
  • Do not put time critical application logic in finalize(), seeing its unpredictability.
  • Do not use Runtime.runFinalizersOnExit(true); as it can put your system in danger.
  • Catch and log exceptions by yourself as the system will ignore them.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=416132&siteId=1