0

Possible Duplicate:
How to prevent an object from getting garbage collected?
In java when does an object become unreachable?

I got asked this question in an interview :

What should I do to to an object so that it becomes unreachable to the garbage collector ?

Community
  • 1
  • 1
user2434
  • 6,339
  • 18
  • 63
  • 87
  • 8
    The concept of "unreachable to the GC" doesn't even exist, and the concept of "unreachable object" means that it is eligible for garbage collection. This sounds intentionally phrased to confuse, in other words, *Yet another lame interview question (TM)*. – Marko Topolnik Oct 31 '12 at 11:51
  • Create a Singleton object which writes all its Data in the finalize(); Methode to the Disk, and reads it if it exists in the private Constructor. – CloudyMarble Oct 31 '12 at 11:55
  • @MeNoMore And how does that prevents GC? The question is not about saving state is about preventing gc, isnt't? – Edwin Dalorzo Oct 31 '12 at 11:57
  • @Marko's right, the question is ridiculous without a use case. If you want to prevent an object from being GCed, *just keep a reference to it*; otherwise the solution should follow from the reason why you can't do that. – millimoose Oct 31 '12 at 12:00
  • 1
    (It's probably telling of a workplace when their interview questions are ones that would get closed on SO were they not prefixed with "this is an interview question".) – millimoose Oct 31 '12 at 12:00
  • @Edwin Dalorzo: why would anyone otherwise need to prevent the GC from cleaning the object? – CloudyMarble Oct 31 '12 at 13:57
  • @Marko If you make a JNI call to a library written in C++, then C++ objects might be created in the native code that the GC has no knowledge of. Wouldn't this produce an "object" that is "unreachable" from the perspective of the gc? (admittedly not a java object) – Gus Nov 03 '12 at 21:48

3 Answers3

1

No object is 'unreachable' by the garbage collector as far as I am aware. However the GC will only collect items, which have no more references pointing to them.

So to 'secure them', either declare them as final (constants), or make sure, that there's a reference pointing to the variable at all times, for example by including the reference in the main operation loop.

ATaylor
  • 2,598
  • 2
  • 17
  • 25
1

The GC will manage any object in the heap. You can make an object always reachable and there-for not collected by the GC, but you can't make an object beyond the GCs reach.

The only way to make data unreachable is to make it off heap in native memory, write it to disk, or pass it to another process.

BTW, Even distributed RMI objects proxied in another process can be cleaned up by the GC when they are no longer used.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Make it contain a static reference to itself (singleton pattern for instance).

richardtz
  • 4,993
  • 2
  • 27
  • 38