简体   繁体   中英

Interview on Garbage Collection in Java

I was recently asked a question on Garbage Collection in JAVA. It goes like-if I have three variable (say), a,b,c as shown below. Then in what order these will be Garbage Collected.

class Test{

static String a;

private String b;

Test(String a, String b)

{
    this.a=a;
    this.b=b;
}

void disp(){

    System.out.println(a+" "+ b);
}

public static void main(String[] args){

    String c="Not you Again";
    Test t= new Test("Hello","World");

    t.disp();
    System.out.println("Value of c = "+c);
}

}

I am aware of the Garbage Collection basics like Young Gen, Middle Gen & Perm Gen and how the objects are moved among them and collected. But Garbage Collection on Variables is something I am alien to. Please help!

All three string variables will be garbage-collected when the VM damn pleases, if it ever damn pleases, and nobody has any control over that. Anyone claiming that they know when or even if these strings will be garbage-collected is lying.

The values referenced by Test.a , tb or c won't ever be garbage collected, because they're all still in scope when main finishes running. That is, the VM exits without garbage collecting them.

As for the parameters a and b in the Test constructor, they could possibly be garbage collected, but it's very unlikely. This particular program is going to finish far too quickly for the garbage collector to even start.

Garbage collector will never run in this particular example. Garbage collector runs only when there is no active thread alive, in this example there is no dead thread thus, garbage collector will never run. Garbage collector is activated by JVM only and we cannot control it, although we can just make a request to run it,this request can be ignored by JVM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM