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:
- If garbage collector destroyed myMap without
close()
than it should executeclear()
method - 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?
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 yourfinalize()
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.