class Book {
boolean checkedOut = false;
Book(boolean checkOut) {
checkedOut = checkOut;
}
void checkIn() {
checkedOut = false;
}
public void finalize() {
if(checkedOut)
{
System.out.println("Error1: checked stat:"+checkedOut);
}
else
{
System.out.println("Error2: checked out:"+checkedOut);
}
}
}
public class TerminationCondition {
public static void main(String[] args) {
Book novel = new Book(true);
// Proper cleanup:
novel.checkIn();
// Drop the reference, forget to clean up:
Book nove2 = new Book(true);
// Proper cleanup:
nove2.checkIn();
// Drop the reference, forget to clean up:
nove2=null;
new Book(true); // nove3
// Force garbage collection & finalization:
System.gc();
}
执行结果如下:
Error2: checked out:false // nove2被回收
Error1: checked stat:true // nove3被回收
引用自jackychen_king(jacky)前辈!
请问如果不用System.gc(),finalize()函数就不会去清理了?会默认回收一部分垃圾吗?
system.gc只是告诉系统要强制回收内存,但是对于某个具体的对象,什么时间回收是系统确定的. 请问下,这个确定值是那些内容呢?
初来乍道,请大家多多指教!
boolean checkedOut = false;
Book(boolean checkOut) {
checkedOut = checkOut;
}
void checkIn() {
checkedOut = false;
}
public void finalize() {
if(checkedOut)
{
System.out.println("Error1: checked stat:"+checkedOut);
}
else
{
System.out.println("Error2: checked out:"+checkedOut);
}
}
}
public class TerminationCondition {
public static void main(String[] args) {
Book novel = new Book(true);
// Proper cleanup:
novel.checkIn();
// Drop the reference, forget to clean up:
Book nove2 = new Book(true);
// Proper cleanup:
nove2.checkIn();
// Drop the reference, forget to clean up:
nove2=null;
new Book(true); // nove3
// Force garbage collection & finalization:
System.gc();
}
执行结果如下:
Error2: checked out:false // nove2被回收
Error1: checked stat:true // nove3被回收
引用自jackychen_king(jacky)前辈!
请问如果不用System.gc(),finalize()函数就不会去清理了?会默认回收一部分垃圾吗?
system.gc只是告诉系统要强制回收内存,但是对于某个具体的对象,什么时间回收是系统确定的. 请问下,这个确定值是那些内容呢?
初来乍道,请大家多多指教!
某个对象回收是在其生命周期结束之时但和finalize没有直接关联了
某对象的finalize方法的调用是受垃圾回收器管制的正如程序中三例 nove1是没有执行finalize 其余两者因为对象已无引用
在gc之后均调用了finalize