The quick answer is no. GC doesn't care about Closeable
.
Java has a protected void finalize() throws Throwable { }
method that you can override and it will be called in the GC. This is a kind of work, for example. in FileInputStream
:
protected void finalize() throws IOException { if ((fd != null) && (fd != FileDescriptor.in)) { runningFinalize.set(Boolean.TRUE); try { close(); } finally { runningFinalize.set(Boolean.FALSE); } } }
The problem is that it creates more problems than it's worth: for example, the JVM does not guarantee that it will ever call this method. That is, you should never use it to process resources; what you see above is a security network to make file handler leaks less damaging.
Another problem will be that the static field will not collect garbage , i.e. while your class will be visible. Thus, you have no way to use finalization.
However, you can use Runtime.addShutdownHook()
- it will add another layer of security networks to your application, giving you the ability to correctly close the connection when you exit. Given that you are using a static field, the lifetime of your connection is likely to be the same as for the JVM.
I would recommend considering the approach, however.
source share