谈谈Java中的Garbage collection(200分)

  • 主题发起人 主题发起人 cheka
  • 开始时间 开始时间
C

cheka

Unregistered / Unconfirmed
GUEST, unregistred user!
对Java的garbage collection机制的认识比较模糊,它不同于Delphi或C++的析构,
今早上看了一道题,就更不明白了,谁来谈谈?
Q12.
1.public void count(){
2. for(int i=1;i<10;i++){
3. String tmp=Integer.toString(i);
4. System.out.println(tmp);
5. }
6. System.out.println("BOOM!");
7.}
When the program reaches line 6,how many of the String objects created in line 3 are eligible for garbage collection?(Assume the System.out object is not keeping a reference)
(a)None
(b)1
(c)8
(d)9
The answer mentioned is (c).Should'nt it be (d) because,8 objects are eligible for garbage collection when control is within the for loop scope.Once control moves out of the for block scope,the reference to the ninth object is lost thus,making the last String object(ninth object)too eligiible for garbage collection.
 
cheka越混越瞎,终于没人疼没人爱了.嘿嘿
这题是在哪得到的?
 
只知道书上是这样说的:
当一个对象不被全局内的其他任何对象引用时就成了无用对象,java的回收内存的机制就
会释放它的存储空间,但因为计算是否“无用”和回收的过程会占用机器时间,所以只有
当必要和存储空间紧张时,才会进行所谓回收,所以尽管有9个string对象(块内),且在
6已经没有对它们的引用,garbage collection 却未必工作。程序结束时也会释放。前几天
的问题里说到“applet越来越慢”的,可能也是这个原因。
 
强制
public static void gc()
Runs the garbage collector.
Calling the gc method suggests that the Java Virtual Machine expend effort
toward recyclingunused objects in order to make the memory they currently
occupy available for quick reuse.
When control returns from the method call, the Java Virtual Machine has made a
best effort to reclaim space from all discarded objects.
The call System.gc() is effectively equivalent to the call:
Runtime.getRuntime().gc()
 
接受答案了.
 
后退
顶部