Kamal
Kamal

Reputation: 4088

Everlasting java object

Is it possible to create an object which will be alive till the JVM is not shut down? Or is there any java objects which remains alive till the JVM is not shutdown.

Upvotes: 1

Views: 199

Answers (4)

cHao
cHao

Reputation: 86535

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.)

Upvotes: 0

Favonius
Favonius

Reputation: 13984

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

Upvotes: 0

Bozho
Bozho

Reputation: 597234

You can be fairly certain that a static field will not be garbage collected. See this question for details.

Upvotes: 6

LaGrandMere
LaGrandMere

Reputation: 10359

The main Thread of your program is always alive until the JVM shuts down.

Why are you asking this question ?

Upvotes: 1

Related Questions