Java中finalize方法的问题[重复]

Posted

技术标签:

【中文标题】Java中finalize方法的问题[重复]【英文标题】:Problems with finalize method in Java [duplicate] 【发布时间】:2019-04-10 11:48:58 【问题描述】:

我在上次练习中遇到了 finalize 方法的问题。好像我有一个不推荐使用的方法,我似乎找不到最新版本的 finalize。我有两个文件,我需要调用“finalize”方法。有人可以给我一个 finalize 方法的例子或帮助我吗?这是我的代码:

public class RoomOccupancy 

    private int numberInRoom;
    private static int totalNumber;
    private double roomCharges;
    private boolean finalizeCalled;

    public RoomOccupancy () 
        this.numberInRoom = 0;
        this.totalNumber = 0;
        this.roomCharges = 0;
        this.finalizeCalled = false;
        System.out.println ( "Room Occupancy - default/no argument constructor" );
    

    public RoomOccupancy (int number, double rCharges) 
        numberInRoom = number;
        roomCharges = rCharges;
        finalizeCalled = false;
        System.out.println ( "Room Occupancy - Overloaded/2-argument constructor" );
    

    public static int getTotal () 
        return totalNumber;
    

    public void addOneToRoom () 
        numberInRoom++;
        totalNumber++;
    

    public void removeOneFromRoom () 
        numberInRoom--;
        totalNumber--;
    

    public int getNumber () 
        return numberInRoom;
    

    public void setNumber (int number) 
        this.numberInRoom = number;
    

    public double getCharges () 
        return roomCharges;
    

    public void setCharges (double rCharges) 
        this.roomCharges = rCharges;
    

    public String toString () 
        String c;
        c = " " + numberInRoom + " " + roomCharges + " ";
        return c;
    

    public boolean equals ( Object obj ) 
        if ( this == obj ) return true;

        if (( obj != null) && ( getClass() == obj.getClass())) 
            RoomOccupancy d = ( RoomOccupancy ) obj;

            if (( numberInRoom == d.numberInRoom) &&
                ( totalNumber == d.totalNumber) &&
                ( roomCharges == d.roomCharges)) 
                return true;
            
            else 
                return false;
            

        
        else 
            return false;
        

    

    public void finalize ( ) 
        if ( !finalizeCalled ) 
            // Do cleanup
        
        System.out.println ( "Course - finalize method" );

    

    public void dispose ( ) 
        //Do cleanup
        finalizeCalled = true;
        System.out.println ( "Course - finalize method" );
    

import java.text.DecimalFormat;

public class RoomOccupancyTest 

    public static void main ( String [] args ) 

        RoomOccupancy noOccupancy = new RoomOccupancy ( );
        System.out.println ("No Occupancy =" + noOccupancy);
        RoomOccupancy roomA = new RoomOccupancy(0, 100.00);
        RoomOccupancy roomB = new RoomOccupancy(0, 200.00);
        RoomOccupancy roomC = new RoomOccupancy(0, 250.00);
        DecimalFormat patternCharges = new DecimalFormat("#####0.00");

        System.out.println ("Five people have checked into room A at $100.00 per person\n" +
                            "Four people have checked into room B at $200.00 per person.\n" +
                            "Three people have checked into room C at $250.00 per person.");
        roomA.addOneToRoom();
        roomA.addOneToRoom();
        roomA.addOneToRoom();
        roomA.addOneToRoom();
        roomA.addOneToRoom();
        roomB.addOneToRoom();
        roomB.addOneToRoom();
        roomB.addOneToRoom();
        roomB.addOneToRoom();
        roomC.addOneToRoom();
        roomC.addOneToRoom();
        roomC.addOneToRoom();

        System.out.println ("Room A holds " + roomA.getNumber() + " The total charge is: $" + (patternCharges.format(roomA.getCharges() * roomA.getNumber())));
        System.out.println ("Room B holds " + roomB.getNumber() + " The total charge is: $" + (patternCharges.format(roomB.getCharges() * roomB.getNumber())));
        System.out.println ("Room C holds " + roomC.getNumber() + " The total charge is: $" + (patternCharges.format(roomC.getCharges() * roomC.getNumber())));
        System.out.println ("Total in all rooms is " + RoomOccupancy.getTotal());

        System.out.println ("One person from each room has left.");
        roomA.removeOneFromRoom();
        roomB.removeOneFromRoom();
        roomC.removeOneFromRoom();

        System.out.println ("Room A holds " + roomA.getNumber() + " The total charge is: $" + (patternCharges.format(roomA.getCharges() * roomA.getNumber())));
        System.out.println ("Room B holds " + roomB.getNumber() + " The total charge is: $" + (patternCharges.format(roomB.getCharges() * roomB.getNumber())));
        System.out.println ("Room C holds " + roomC.getNumber() + " The total charge is: $" + (patternCharges.format(roomC.getCharges() * roomC.getNumber())));
        System.out.println ("Total in all rooms is " + RoomOccupancy.getTotal());

        if (roomA == roomB)
            System.out.println ("Room A and B are the same object."); // NOT EXPECTED
        if (roomA == roomC)
            System.out.println ("Room A and C are the same object."); // NOT EXPECTED
        if (roomB == roomC)
            System.out.println ("Room B and C are the same object."); // NOT EXPECTED
        else
            System.out.println ("No rooms are the same object."); // EXPECTED

        if (roomA.equals (roomB))
            System.out.println ( "Room A and B are EQUAL."); // NOT EXPECTED
        if (roomA.equals(roomC))
            System.out.println ( "Room A and C are the EQUAL."); // NOT EXPECTED
        if (roomB.equals(roomC))
            System.out.println ( "Room B and C are the EQUAL."); // NOT EXPECTED
        else
            System.out.println ( "No Rooms are EQUAL."); // EXPECTED

        roomA.finalize();
        roomB.finalize();
        roomC.finalize();

        roomA = roomB = roomC = null;
        System.gc();


    

【问题讨论】:

finalize 自 Java 9 起已弃用。尽管您仍然可以使用它,但不建议这样做,并且将来可能会被删除。你到底想用这种方法做哪些其他地方做不到的事情? 如果您对它被弃用的原因感兴趣,documentation。如果内部最终确定,则不需要每个对象仅调用一次!使用@Override 是一个好习惯。您不需要 this.numberInRoom = 0; this.totalNumber = 0; this.roomCharges = 0; this.finalizeCalled = false; 在构造函数中。这些是默认值,将自动分配。 " 我有两个文件,需要调用 'finalize' 方法。" 为什么? finalize 的用例一直是有限的,您的代码没有理由使用 finalize。 【参考方案1】:

finalize 自 Java 9 起已弃用。您可以在 javadoc:-

中了解原因和替代方案

已弃用。最终确定机制本质上是有问题的。 最终确定会导致性能问题、死锁和挂起。 终结器中的错误可能导致资源泄漏;没有办法 如果不再需要,取消定稿;并且没有排序是 在调用中指定以完成不同对象的方法。 此外,没有关于时间的保证 定稿。 finalize 方法可能会在 finalizable 上调用 只有在无限期延迟之后才反对,如果有的话。类 持有非堆资源的实例应该提供一种方法来启用 显式释放这些资源,它们还应该实现 如果合适,可自动关闭。 Cleaner 和 PhantomReference 提供 更灵活高效的方式来释放对象时的资源 变得无法访问。

您不应该使用这种方法。其实你不需要!

如果您仍然想使用它,请忽略警告或在您的方法中添加以下内容以隐藏警告:-

@SuppressWarnings( "deprecation" )

【讨论】:

我同意 100% 但是我在上次练习中弄错了那部分,我正在努力做得更好。只是很难弄清楚。 @BK 然后使用它并忽略警告。我可以问一下您需要做什么“清理”吗? 任务非常模糊,只是说使用“'finalize'方法”。最重要的是,这本书对这个主题只字未提。大声笑我会按照你和其他人的说法,忽略不推荐使用的错误,我将在练习前说明它是一种不推荐使用的方法。感谢您的帮助。

以上是关于Java中finalize方法的问题[重复]的主要内容,如果未能解决你的问题,请参考以下文章

JAVA之旅——final关键字 , 抽象类abstract,模板方法模式,接口interface,implements,特点,扩展

java中的final类是不是与所有方法都声明为final且所有变量都声明为private的类相同[重复]

java为啥需要finally?

final关键字解析&匿名内部类形参用final

与 C# 相比,Java 的 final 类似于 const 或 readonly [重复]

final 关键字