Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unload static fields

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?

like image 778
Alina Danila Avatar asked Nov 19 '11 17:11

Alina Danila


People also ask

Can static fields be final?

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.

Do static variables get garbage collected?

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.

Can static fields be private?

Just like an instance variables can be private or public, static variables can also be private or public.

How do you reset a static class in Java?

You can try this. Main MainObject = new Main; MainObject. main(args); It will restart the class again and again until you stop the class.


2 Answers

In a web app, you would use a ServletContextListener.

like image 92
Skip Head Avatar answered Oct 14 '22 20:10

Skip Head


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.

like image 32
rsp Avatar answered Oct 14 '22 19:10

rsp