首页 > 解决方案 > 孤立岛上的垃圾收集

问题描述

根据我的理解,任何没有引用的对象都有资格进行垃圾收集,即在收集垃圾时应该调用类的 finalize 方法。我在下面有一个类和一个问题,为什么主类中没有引用的线程对象在垃圾收集时没有调用 finalize 方法,如果它调用了。

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");
    }

    
}

编辑:new Thread() {//blah blah }.start(); 是一个被创建的堆的非引用对象。即它没有堆栈引用。理论上,任何非堆栈引用的对象都有资格进行垃圾收集,这实际上适用于垃圾收集。由于它们没有被堆栈引用,因此它也被视为孤立岛。

想知道我在这方面的理解是否错误。谢谢。如果我的想法是矛盾的,请分享您的观点。

标签: javamultithreadinggarbage-collectionheap-memoryjava-memory-model

解决方案


为什么主类中没有引用的线程对象没有调用finalize

垃圾收集器将活动线程视为活动线程,即使没有其他任何东西引用这些线程。

换句话说,垃圾回收不会使正在运行的代码突然终止。如果是这样,那将是一个非常令人头疼的问题。

最重要的是,您只finalize在一个从未实例化的类上实现。


推荐阅读