进行垃圾回收的情况:
1、对象被设置为null;
2、对象设置为nul且方法的运行周期结束
在Object类下面有一个finalize()方法用于垃圾处理,所以所有类都有自己的finalize()方法,垃圾处理是不可预知性的,它由一个低优先级的线程监测什么时候进行垃圾收集。
垃圾回收是在程序运行过程中进行的
一、
1. class Test {
2. private Demo d;
3. void start() {
4. d = new Demo();
5. this.takeDemo(d);
6. }
7.
8. void takeDemo(Demo demo) {
9. demo = null;
10. demo = new Demo();
11. }
12. }
When is the Demo object, created on line 3, eligible for garbage collection?
这个程序是在程序运行过程中收集内存,因为在第9行设置demo为null,而在第10行又生成了对象demo,在第9行时就进行了一次垃圾回收
二、
Given:
10. public Object m() {
11. Object o = new Float(3.14F);
12. Object [] oa = new Object[1];
13. oa[0] = o;
14. o = null;
15. return oa[0];
16. }
When is the Float object, created in line 11, eligible for garbage collection?
A. Just after line 13.
B. Just after line 14.
C. Never in this method.
D. Just after line 15 (that is, as the method returns).
Answer: B
本程序中在第14行把对象o设置为null值后就符合垃圾回收机制了,所以在第14行时进行垃圾回收处理
三、
QUESTION NO: 76
Given:
1. class Bar { }
1. class Test {
2. Bar doBar() {
3. Bar b = new Bar();
4. return b;
5. }
6. public static void main (String args[]) {
7. Test t = new Test();
8. Bar newBar = t.doBar();
9. System.out.println(“newBar”);
10. newBar = new Bar();
11. System.out.println(“finishing”);
12. }
13. }
At what point is the Bar object, created on line 3, eligible for garbage collection?
A. After line 8.
B. After line 10.
C. After line 4, when doBar() completes.
D. After line 11, when main() completes.
Answer: C
当方法返回 得到参数时 方法的生命周期就销毁了 所以当执行完Bar newBar = t.doBar(); 这句后 Bar就没引用了 所以是垃圾
我现在正在准备考SCJP,由于垃圾收集这块在SCJP中占的比例不小所有就下了点功夫写了这些东东,这些例题都是我从模拟题上看的,然后通过自己理解的和大家分享,如果谁还有更详细的资料希望能共享资源,我的E-mail:
lei8704@163.com QQ:576525789
不好就给鸡蛋