Using Singleton Class
In case of a singleton class, the reference of the only object created can be stored in a static reference. Since static members are stored in class area (a memory segment), their lifetime spans the lifetime of the program. The following program explains how to do it:
public class Singleton {
/* static class member which
will store the object reference*/
private static Singleton uniqueInstance;
private Singleton()
{
}
public static synchronized Singleton getInstance()
{
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqInstance;
}
}
The above example shows that since the object’s reference has been passed into a static variable, it will never be lost. Therefore, the object won’t be deleted until the end of the program. However, the only issue remains that only one object can be created here.
Using public void finalise()
Finalize is a call-back method (a method called by the JVM, and not by the user), that is last method executed on an object. A subclass may override the finalize method to dispose of system resources or to perform other cleanup.
How to prevent garbage collection using finalize?
Method 1
The finalize method of a class can be overridden to preserve the reference of the object that is about to be deleted. The following program demonstrates, how:
class A {
static A y;
void f()
{
A x = new A();
}
pubic void finalize()
{
y = this; // Putting the reference id
// of the current object
// into the static variable y
System.out.println("Object reference saved. The object
won't be collected by the garbage collector");
}
public static void main(String a[])
{
f(); // function called
}
As explained previously, finalize is the last method that is executed on an object. In the above program, the function ‘f()’ creates a local object of class A. When the call of the function terminates, the scope of the variable ‘x’ terminates as well, and hence, is marked for collection by the garbage collector. However, before the garbage collector could delete the object, finalize runs.
Inside the body of the method ‘finalize’, one can see that the static member of class A, ‘y’, is assigned the reference id of the current object. As a result, the reference id of the object to be deleted is preserved, and hence, the object is not deleted.
Method 2
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();
@Override
protected void finalize() throws Throwable {
while (true) {
Thread.yield();
}
}
参考:
《How to prevent objects of a class from Garbage Collection in Java》
《How to prevent an object from getting garbage collected?》