class Robot
{
long memory[] = new long[9923372];
private String name;
Robot(String nm) throws Exception
{
name = nm;
System.out.println("name = " + name);
}
protected void finalize()
{
System.out.println("\nBye - Bye ---eeeee " + name+"\n");
}
}
class Test
{
public static void main(String sdf[]) throws Exception
{
int i=1;
Robot robot1;
while(true)
{
//finalizer runs before the dereference of rajni - 1
robot1= new Robot("Rajni - "+i++);
Thread.sleep(1000);
}
}
}
how can finalizer run before derefernce of robot1 from rajni1 first object ...
the loop runs in the infinite loop...
i know that garbage collector runs whenever heap space is low and more memory is required for the object allocation...but the condition is that there must be some dereferenced object residing in memory .....
--->run in jre 32 bit to get the given output ... you better know why??
It is clearer now you have provided the output.
You can look at the compiled byte code to see why.
public static main([Ljava/lang/String;)V throws java/lang/Exception
L0
LINENUMBER 48 L0
ICONST_1
ISTORE 1
L1
LINENUMBER 54 L1
FRAME APPEND [I]
NEW Main$Robot
DUP
NEW java/lang/StringBuilder
DUP
INVOKESPECIAL java/lang/StringBuilder.<init> ()V
LDC "Rajni - "
INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
ILOAD 1
IINC 1 1
INVOKEVIRTUAL java/lang/StringBuilder.append (I)Ljava/lang/StringBuilder;
INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
INVOKESPECIAL Main$Robot.<init> (Ljava/lang/String;)V
ASTORE 2
L2
LINENUMBER 55 L2
LDC 1000
INVOKESTATIC java/lang/Thread.sleep (J)V
GOTO L1
L3
LOCALVARIABLE sdf [Ljava/lang/String; L0 L3 0
LOCALVARIABLE i I L1 L3 1
LOCALVARIABLE robot1 LMain$Robot; L2 L3 2
MAXSTACK = 4
MAXLOCALS = 3
The important line to note is the scope of the robot1
variable which is between L2
and L3
i.e. only during the Thread.sleep(1000);
and the local variable is out of scope as soon as the loop jumps back to L1
This means the variable in reality is available to be GC-ed at the top of the loop, not after the new Robot has been created as you might imagine.