How to prevent an object from getting garbage collected?
Are there any approaches by finalize or phantom reference or any other approaches?
I was asked this question in an interview. The interviewer suggested that finalize()
can be used.
How to prevent an object from getting garbage collected?
Are there any approaches by finalize or phantom reference or any other approaches?
I was asked this question in an interview. The interviewer suggested that finalize()
can be used.
Hold a reference. If your object is getting collected prematurely, it is a symptom that you have a bug in the design of your application.
The garbage collector collects only objects to which there is no reference in your application. If there is no object that would naturally reference the collected object, ask yourself why it should be kept alive.
One usecase in which you typically have no references, but want to keep an object is a singleton. In this case, you could use a static variable. One possible implementation of a singleton would look like this:
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqInstance;
}
}
Edit: Technically, you can store a reference somewhere in your finalizer. This will prevent the object from being collected until the collector determines again that there are no more references. The finalizer will only be called at most once, however, so you must ensure that your object (including its superclasses) need not be finalized after the first collection. I would advise you, however, not to use this technique in actual programs. (It will leave colleagues like me yelling WTF!? ;)
protected void finalize() throws Throwable {
MyObjectStore.getInstance().store(this);
super.finalize(); // questionable, but you should ensure calling it somewhere.
}
The trick answer your interviewer was looking for is probably that he wants you to know that you can prevent garbage collection from removing an object by forcing a memory leak.
Obviously, if you keep a reference to the object in some long-lived context, it won't be collected, but that's not what the OP's recruiter asked about. That's not something which happens in the finalize method.
What you can do to prevent garbage collection from within the finalize method is to write an infinite loop, in which you call Thread.yield();
(presumably to keep an empty loop from being optimized away):
@Override
protected void finalize() throws Throwable {
while (true) {
Thread.yield();
}
}
My reference here is an article by Elliot Back, in which describes forcing a memory leak by this method.
Just another way in which finalize methods are evil.
The best way is to use Unsafe, although ByteBuffer
might be a possible workaround for some cases.
Also search for the keyword "off-heap" memory.
Unsafe
Advantages over ByteBuffer
:
It is not however easy to get working. The method is described in the following articles:
They all consist of the following steps:
we need a sizeof
operator, which Unsafe does not have. How to make one was asked at: In Java, what is the best way to determine the size of an object?. The best options is likely the instrument
API, but that requires you to create a Jar and use special command line options...
once we have sizeof
, allocate enough memory with Unsafe#allocateMemory
, which is basically a malloc
and returns an address
create a regular on heap object, copy it to the allocated memory with Unsafe#copyMemory
. To do this, you need to the address of the on-heap object, and the size of the object
set an Object
to point to the allocated memory, then cast the Object
to your class.
It does not seem possible to set the address of a variable directly with Unsafe, so we need to wrap the object into an array or wrapper object, and use Unsafe#arrayBaseOffset
or Unsafe#objectFieldOffset
.
once you are done, free the allocated memory with freeMemory
If I ever get this to not segfault I will post an example :-)
ByteBuffer
Advantages over Unsafe:
JLS says:
The contents of direct buffers may reside outside of the normal garbage-collected heap.
Example of usage with primitives:
ByteBuffer bb = ByteBuffer.allocateDirect(8);
bb.putInt(0, 1);
bb.putInt(4, 2);
assert bb.getInt(0) == 1;
assert bb.getInt(4) == 2;
// Bound chekcs are done.
boolean fail = false;
try {
bb.getInt(8);
} catch(IndexOutOfBoundsException e) {
fail = true;
}
assert fail;
Related threads:
If there is still a reference to the object, it won't get garbage collected. If there aren't any references to it, you shouldn't care.
In other words - the garbage collector only collects garbage. Let it do its job.
I suspect what you might be referring to is if your finalize
method stashes away a reference to the object being finalized. In this case (if my reading of the Java Language Spec is correct) the finalize
method will never be re-run, but the object will not yet be garbage collected.
This is not the sort of thing one does in real life, except possibly by accident!
This sounds like one of those interview-only-time-you'll-see-it questions. finalize() is run when your object is getting garbage collected, so it'd be pretty perverse to put something in there to prevent collection. Normally you just hold a reference and that's all you need.
I'm not even sure what would happen if you'd create a new reference for something in the finalizer - since the garbage collector's already decided to collect it would you then end up with a null ref? Seems like a poor idea, in any case. e.g.
public class Foo {
static Foo reference;
...
finalize (){
reference = this;
}
}
I doubt this would work, or it might work but be dependant on the GC implenetation, or be "unspecified behavior". Looks evil, though.
The key point is if we set the real reference variable pointing to the object null,although we have instance variables of that class pointing to that object not set to null. The object is automatically eligible for garbage collection.if save the object to GC, use this code...
public class GcTest {
public int id;
public String name;
private static GcTest gcTest=null;
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("In finalize method.");
System.out.println("In finalize :ID :"+this.id);
System.out.println("In finalize :ID :"+this.name);
gcTest=this;
}
public static void main(String[] args) {
GcTest myGcTest=new GcTest();
myGcTest.id=1001;
myGcTest.name="Praveen";
myGcTest=null;
// requesting Garbage Collector to execute.
// internally GC uses Mark and Sweep algorithm to clear heap memory.
// gc() is a native method in RunTime class.
System.gc(); // or Runtime.getRuntime().gc();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\n------- After called GC () ---------\n");
System.out.println("Id :"+gcTest.id);
System.out.println("Name :"+gcTest.name);
}
}
Output :
In finalize method.
In finalize :ID :1001
In finalize :ID :Praveen
------- After called GC () --------
Id :1001
Name :Praveen
I wonder if what they're going for is the pattern with resource pools (e.g. for network/db connections, or threads) where you use finalize to return a resource to the pool so that the actual object holding the resource isn't GC'ed.
Stupid example, in Java-like pseudocode and missing any kind of synchronization:
class SlowResourceInternal {
private final SlowResourcePool parent;
<some instance data>
returnToPool() {
parent.add(this);
}
}
class SlowResourceHolder {
private final SlowResourceInternal impl;
<delegate actual stuff to the internal object>
finalize() {
if (impl != null) impl.returnToPool();
}
}
I believe there is a pattern out there for this. Not sure if it the factory pattern. But you have one object that creates all your objects and holds a reference to them. When you are finished with them, you de-reference them in the factory, making the call explicit.
We have three ways to achieve same - 1) Increasing the Heap -Eden space size . 2) Create Singleton class with Static reference . 3) Override finalize() method and never let that object dereference.