Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

java - In the given program the Garbage collector is running before the object is dereferenced...using jre 7(32-bit)

enter image description here

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("
Bye - Bye ---eeeee " + name+"
");
}

}


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??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...