什么时候一个对象可以被垃圾回收?
Java 垃圾回收器跟踪活动对象,并且不再需要的对象会被标记为垃圾回收。它使开发人员不必考虑内存分配/释放问题。
当在 Java 程序中创建的对象不再可达或使用时,它就可以被垃圾回收。
以下是一些 Java 对象可能无法访问/未使用的情况。
方法内部的对象 − 在 Java 中,方法存储在栈内存中。当您调用一个方法时,JVM 将其提取到栈中并执行它。执行完成后,它将从栈中弹出,然后其所有变量都将被丢弃。
因此,当您在方法中创建对象时,在方法执行完成后,此对象将变得不可访问。
示例
public class Sample {
String name;
Sample(String name){
this.name = name;
}
public static void sampleMethod(){
Sample obj1 = new Sample("myObject2");
Sample obj = new Sample("myObject1");
}
protected void finalize() throws Throwable {
System.out.println(this.name + " successfully garbage collected");
}
public static void main(String args[]){
sampleMethod();
System.gc();
}
}输出
myObject1 successfully garbage collected myObject2 successfully garbage collected
重新赋值 − 当您将一个值(另一个对象)重新赋值给现有的引用变量时,原始对象最终将变得不可访问。
示例
public class Sample {
String name;
Sample(String name){
this.name = name;
}
protected void finalize() throws Throwable {
System.out.println(this.name + " successfully garbage collected");
}
public static void main(String args[]){
Sample obj = new Sample("myObject1");
obj = new Sample("myObject2");
System.gc();
}
}输出
myObject1 successfully garbage collected
赋值为 null − 当您将 null 值赋值给对象的引用时,它将不再可访问。
示例
public class Sample {
String name;
Sample(String name){
this.name = name;
}
protected void finalize() throws Throwable {
System.out.println(this.name + " successfully garbage collected");
}
public static void main(String args[]){
Sample obj = new Sample("myObject1");
obj = null;
System.gc();
}
}输出
myObject1 successfully garbage collected
匿名对象 − 实际上,匿名对象的引用不会存储在任何地方,因此在第一次执行后您无法再次调用它,因此它不可访问。
示例
public class Sample {
String name;
Sample(String name){
this.name = name;
}
public void sampleMethod(){
System.out.println("This is a sample method");
}
protected void finalize() throws Throwable {
System.out.println(this.name + " successfully garbage collected");
}
public static void main(String args[]){
new Sample("object1").sampleMethod();
System.gc();
}
}输出
This is a sample method object1 successfully garbage collected
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP