According to my understanding any object without a reference is eligible for garbage collection i.e The class's finalize method should be called while collecting the garbage. I have a class below and a question why the thread objects with no reference in the main class are not calling finalize Method while garbage collection if it did.
package com;
class Customer {
int amount = 10000;
synchronized void withdraw(int amount) {
System.out.println("going to withdraw...");
if (this.amount < amount) {
System.out.println("Less balance; waiting for deposit...");
try {
wait(10000);
} catch (Exception e) {
}
}
this.amount -= amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount) {
System.out.println("going to deposit...");
this.amount += amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test {
public static void main(String args[]) throws InstantiationException, IllegalAccessException {
final Customer c = new Customer();
//Island of Isolating a Thread
new Thread() {
public void run() {
// System.out.println("withdraw thread ");
c.withdraw(15000);
}
}.start();
//Island of Isolating another Thread
new Thread() {
public void run() {
// System.out.println("deposit thread ");
c.deposit(10000);
}
}.start();
//attempting to gc manually.
System.gc();
}
//Calling a finialize() method to check whether it is garbage collected or not
protected void finalize() throws Throwable {
System.out.println("Finalize method called");
}
}
Edit: new Thread() {//blah blah }.start(); is an non-referenced object that gets created heap. i.e It has no stack reference. In theory, any non-Stack referenced object is eligible for garbage collection which in fact applicable to garbage collection. Since they are not Stack referenced, Also It is also considered as Island of Isolation.
Wondering if my understanding is wrong in this regard. Thanks. Please share your views if my thinking is contradictory.