Javatpoint Logo

Can the unreferenced objects be referenced again?

By: sreeni*** On: Tue Dec 31 16:58:06 IST 2013     Question Reputation29 Answer Reputation63 Quiz Belt Series Points0  92User Image
Can the unreferenced objects be referenced again? explain how?Up0Down

 
Yes it is possible we can get the reference of unreferenced objects by this keyword in finalize method.
Ex:
class A {
static A a=null;
public static void main(String[] args) {
A b=new A();
System.out.println( b.hashCode() );
b=new A();
System.gc(); //System.out.println( a.hashCode() );
}
public void finalize() {
a=this;
System.out.println( a.hashCode() );
System.out.println("finalize method");
}
}
Image Created0Down

By: [email protected] On: Wed Jan 01 23:17:30 IST 2014 Question Reputation0 Answer Reputation147 Belt Series Points0 147User Image
Are You Satisfied :1Yes1No
 
The finalize() method is called by the garbage collector before releasing the instance from service. It gives the developer a chance to do operations on the instance.

But if we want to have the same object back into the service (without using clone concept)
we can store the current object reference into some other reference variable (in finalize() method) and it will become reachable again.

Example Code : --


public class TestObject {
public String name;
public TestObject(){
this("Ranjan");
}
public TestObject(String name){
this.name = name;
System.out.println("TestObject : " + this);
}
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("finalize : TestObject : " + this);
Test.main = this;
}
}

public class Test {
public static TestObject main;
public static void main(String[] args) {
System.out.println(new TestObject());
System.gc();
System.runFinalization();
System.gc();
System.out.println(main);
}
}

By executing the following code, you can see that finalize() method is getting called, but still we have the same object.
Image Created0Down

By: [email protected] On: Thu Jan 02 11:34:26 IST 2014 Question Reputation0 Answer Reputation359 Belt Series Points0 359User Image
Are You Satisfied :0Yes0No