×

Loading...

Topic

This topic has been archived. It cannot be replied.
  • 工作学习 / IT技术讨论 / question about java garbage collector
    Consider the following code:
    Public void method(String s)
    {
    String a,b;
    a= new String( "Hello");
    b= new String("Goodbye");
    System.out.println(a+b);
    a= null;
    a=b;
    System.out.println(a+b);
    }

    Where the garbage collector will run the first time?
    In line "a=null" or " a=b"?
    I think it will run in "a = null" at first, then "a=b".
    • Let me try.....
      The answer is "I am not sure". After line "a=null", "Hello" is an abandoned, or orphan object. After the whole method is finished, all the Strings introduced in the method will be abandoned.

      The fact that some objects are abandoned (no longer referenced) does not mean they will be garbage collected immediately. They may be claimed at once if your JVM lacks memory. They may float in JVM's memory until you shut down your JVM (done by System.exit(0) or by return in main() method), provided you machine has a big memory.

      Hope this helps.
    • both of them are not correct, the garbage collection will start at the first line of "System.out.println(a+b); " couse "a" and "b" have been invoked
      • disagree with you
        I think the garbage collector will run after the ending of that method.
        though a is set by null ,it doesnot mean a is destroyed but it has a value of null.
        • why not try
          printf somthing in it's finalize function and before/after the assignment, see which print first.
        • You can't tell when the garbage collector will run. You can't even force the garbage collector to run. So the answer should be "don't know"
          • although you cant not farce it run. you DO can recommend garbage collection should run by using System.gc() method but do not guarantee it.
      • Cannot say GC will happen .... But a+b will lead to a String available to be GC.
      • Cannot say GC will happen .... But a+b will lead to a String available to be GC. Actually, even first line :new String("hello") will make "hello" available got GC also.