I have a java class that uses complex static fields which need special operations as close()
so that they are safely cleaned by GC.
For the initialization of static fields I use the static
block. But I don't now how to unload the static field safely, so that I can call the close()
method before the field is cleaned up by GC.
Is there any way to unload a static field, similar to the static initialization block?
Initialize inside a static block : We can also initialize a final static variable inside a static block because we should initialize a final static variable before class and we know that static block is executed before main() method.
Because static variables are referenced by the Class objects which are referenced by ClassLoaders. So, Static variables are only garbage collected when the class loader which has loaded the class in which static field is there is garbage collected in java.
Just like an instance variables can be private or public, static variables can also be private or public.
You can try this. Main MainObject = new Main; MainObject. main(args); It will restart the class again and again until you stop the class.
In a web app, you would use a ServletContextListener.
You can setup a shutdown hook to accomplish this, but you might not be able to complete all actions. You might have run out of memory or the process might have been killed without it giving a chance to cleanup, etc.
It is better to either make sure your data consistence doesn't depend on this code and/or to move it to code that cleans up regularly during the lifetime of the application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With