开发者

Everlasting java object

开发者 https://www.devze.com 2023-02-01 05:13 出处:网络
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 fairl

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:

  1. Override protected void finalize() throws Throwable; and Self reference the object in it.
  2. 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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消