Reputation: 1933
I want to know when an object is deallocated in Java?
If there is a something like deinit
in Swift, I can release some resources at there.
ex)
deinit {
myResource1.dispose()
myResource2.release()
someOtherResource.close()
....
}
Is it a bad practice in Java, so that I have to find another way?
Specifically, I want to know when a row in a list view dies.
Upvotes: 2
Views: 3609
Reputation: 3795
Employee class :
class Employee {
public int id;
public Employee(int id) {
// TODO Auto-generated constructor stub
this.id = id;
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
System.out.println(this.id + " Garbage Collected");
}
}
MainClass :
public class TestMain {
public static void main(final String[] args) throws ParseException {
Employee p = new Employee(111);
Employee p2 = new Employee(222);
p = null;
p2 = null;
System.gc();
}
}
N.B : Though its not sure whether garbage collector will be called or not even if we call gc() method
Upvotes: 1
Reputation: 122018
Unlike constructors, there are no destructors or de-init in Java. When the instance is no more reachable (no more references to the object), it will automatically Garbage collects by JVM.
You can try implementing finalize()
method in your Class.
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
Upvotes: 2