在Java中清理Object的最佳方法是什么? [英] What is the best way to clean up an Object in Java?

查看:135
本文介绍了在Java中清理Object的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在Java中没有任何析构函数,就像我们在C ++中一样。

We don't have any destructor in Java as we have in C++.

Q1。我们应该如何清理java中的任何对象。

Q1. How should we clean up any Object in java.

Q2。是否有替代finally块。

Q2. Is there any alternative to a finally block.

Q3。有时我们必须调用explicitely初始化/终止来自我们班级的第三方代码,例如

Q3. Sometimes we have to call explicitely initialization/termination of a third party code from our class e.g.

public classs MyClass{
    public MyClass(){
        ThirdPartyInitialize();
    }

    protected void finalize(){
        ThirdPartyTerminate();
    }
}

这是正确的方法吗?

推荐答案

您通常无法自己清理Java对象。垃圾收集器决定何时清理对象。您可以通过将对象引用设置为 null 来指示何时完成对象引用,但通常只是让它超出范围就足够了。无论哪种方式,您仍然无法控制何时收集垃圾。

You generally cannot "clean up" Java objects yourself. The garbage collector decides when to clean objects up. You can indicate when you are done with an object reference by setting it to null, but generally just letting it go out of scope is good enough. Either way, you still have no control over when it gets garbage collected.

finally 块用于执行是否从尝试块抛出异常的操作,并且是执行清理的最佳位置。通常,您只会清理非对象资源,例如开放流。

The finally block is intended for performing actions whether an exception is thrown from a try block or not, and is the best place to perform clean up. Generally you only would clean up non-object resources like open streams.

finalize()不保证是调用因为在程序退出之前无法保证调用垃圾收集器。它不像C ++析构函数,因为C ++析构函数总是被调用,你可以依赖它们被调用。您不能依赖 finalize()被调用。

finalize() is not guaranteed to be called because the garbage collector is not guaranteed to be called before your program exits. It is not really like a C++ destructor because C++ destructors are always called and you can rely on them being called. You cannot rely on finalize() being called.

所以1)使用 finally 释放非对象资源的块2)让垃圾收集器清理对象资源3)你可以通过将对象设置为来向垃圾收集器提示你已完成对象null 如果它在长时间运行的方法中使用。

So 1) use finally blocks to release non-object resources 2) let the garbage collector clean up object-resources 3) you can hint to the garbage collector that you are done with an object by setting it to null if it is used in a long-running method.

这篇关于在Java中清理Object的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆