Everlasting java object
Is it possible to create an object which will be alive til开发者_如何学Pythonl the JVM is not shut down? Or is there any java objects which remains alive till the JVM is not shutdown.
You can be fairly certain that a static
field will not be garbage collected. See this question for details.
The main Thread of your program is always alive until the JVM shuts down.
Why are you asking this question ?
Every JVM instance has only one java.lang.Runtime
instance. Created at the start and stays till the end. If you want everlasting then there are two ways:
- Override
protected void finalize() throws Throwable;
and Self reference the object in it. - Maintain reference to your object
Of course. All you have to do is make sure the object is reachable by running code, and it won't die. The GC only collects stuff that the code doesn't have a reference to anymore.
A single static reference (that you never set to null) within one of your classes should be enough to guarantee that the object sticks around as long as the app is running. However, as long as you are able to see and use the object, it should stick around anyway. (There's a concept called "weak references" that makes this not always true, but if you're using them, then you wouldn't be asking the question.)
精彩评论