Java的垃圾回收

System.gc()是垃圾回收调用的方法,该方法会去调用对象的finalize()方法。在程序中不用调用System.gc()方法,因为JVM会在适当的时候调用它。如果频繁强制调用则可能由于启动垃圾回收机制而导致消耗过多资源。

public class GcDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Person p = new Person("xiaoming", 18);
		System.out.println(p);
		p = null;
		System.gc();
	}

}

class Person {
	private String name;
	private int age;

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}

	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	protected void finalize() throws Throwable {
		System.out.println("当前资源被释放:" + this);
		super.finalize();
	}
}

 

你可能感兴趣的:(GC,垃圾回收)