如果在一个对象内部产生一个对象,但是又没有对这个对象进行引用,是不是这个对象随时有被gc清除的可能?譬如:
class Aclass {
   public run() 
   {
      Object objB=new AnotherClass();
      
    }
    public static void main(String[] args)
    {  
       Aclass objA=new Aclass();
       objA.run();
       ...     }
}因为run()调用后,objB的可见域已经结束,
这个objB是否随时会被当作垃圾清除?

解决方案 »

  1.   

    我是在看CoreJava里面的一个例子,有这个疑惑的:
     1. import java.awt.*;
     2. import java.awt.event.*;
     3. import java.util.*;
     4. import javax.swing.*;
     5. import javax.swing.Timer;
     6.
     7. public class InnerClassTest
     8. {
     9.    public static void main(String[] args)
    10.    {
    11.       TalkingClock clock = new TalkingClock(1000, true);
    12.       clock.start();
    13.
    14.       // keep program running until user selects "Ok"
    15.       JOptionPane.showMessageDialog(null, "Quit program?");
    16.       System.exit(0);
    17.    }
    18. }
    19.
    20. /**
    21.    A clock that prints the time in regular intervals.
    22. */
    23. class TalkingClock
    24. {
    25.    /**
    26.       Constructs a talking clock
    27.       @param interval the interval between messages (in milliseconds)
    28.       @param beep true if the clock should beep
    29.    */
    30.    public TalkingClock(int interval, boolean beep)
    31.    {
    32.       this.interval = interval;
    33.       this.beep = beep;
    34.    }
    35.
    36.    /**
    37.       Starts the clock.
    38.    */
    39.    public void start()
    40.    {
    41.       ActionListener listener = new TimePrinter();
    42.       Timer t = new Timer(interval, listener);
    43.       t.start();
    44.    }
    45.
    46.    private int interval;
    47.    private boolean beep;
    48.
    49.    private class TimePrinter implements ActionListener
    50.    {
    51.       public void actionPerformed(ActionEvent event)
    52.       {
    53.          Date now = new Date();
    54.          System.out.println("At the tone, the time is " + now);
    55.          if (beep) Toolkit.getDefaultToolkit().beep();
    56.       }
    57.    }
    58. }不过觉得这里的:
        ActionListener listener 
        Timer t 
    两个对象与objB好像又不太一样,listener传给了Timer t,进行了引用,不会被gc清除。
    但是Timer t就有可能了?那位给解释一下?多谢!
      

  2.   

    呵呵,你的意思不正确。
    GC的时候要考虑对象的可触及性。包括强可触及、软可触及、弱可触及等等。你这里的t 和listenner 都属于软可触及,GC要回收的话也是一起回收的。