关于对象的可见域以及垃圾清除的问题。

hjian 2005-06-20 09:54:12
如果在一个对象内部产生一个对象,但是又没有对这个对象进行引用,是不是这个对象随时有被gc清除的可能?譬如:
class Aclass {
public run()
{
Object objB=new AnotherClass();

}
public static void main(String[] args)
{
Aclass objA=new Aclass();
objA.run();
...

}
}

因为run()调用后,objB的可见域已经结束,
这个objB是否随时会被当作垃圾清除?
...全文
38 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
mofeir 2005-06-20
  • 打赏
  • 举报
回复
呵呵,你的意思不正确。
GC的时候要考虑对象的可触及性。包括强可触及、软可触及、弱可触及等等。

你这里的t 和listenner 都属于软可触及,GC要回收的话也是一起回收的。

hjian 2005-06-20
  • 打赏
  • 举报
回复
我是在看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就有可能了?

那位给解释一下?多谢!


mofeir 2005-06-20
  • 打赏
  • 举报
回复
是的。
hui_feng 2005-06-20
  • 打赏
  • 举报
回复
学习中.如果有机会也要指点指点小弟噢.........

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧