你如何在 Java 中编写一个解构器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2450855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you write a deconstructor in Java?
提问by Phoenix
I came across this question and am looking for some ideas?
我遇到了这个问题,正在寻找一些想法?
回答by Daniel Schneller
You do not need (nor should you try to use) destructors - or what they are called in Java: "Finalizers".
您不需要(也不应该尝试使用)析构函数 - 或者它们在 Java 中的名称:“终结器”。
The VM specification does allow for VM implementations to never call them. So they are not reliable for resource releases and the like. Generally speaking the code in the finalize()method of any object can be called by the VM before the object is garbage collected, but as this is not mandatory, you should avoid it.
VM 规范确实允许 VM 实现永远不会调用它们。因此,它们对于资源释放等不可靠。一般来说finalize(),任何对象的方法中的代码都可以在对象被垃圾回收之前被VM调用,但由于这不是强制性的,所以应该避免它。
回答by ChristopheD
Java is garbage-collected, so there is no way to tell when your destructorwould be called (when your object will be garbage-collected).
Java 是垃圾收集的,因此无法确定何时调用析构函数(何时对对象进行垃圾收集)。
There is a finalize(inherited) method but you can't rely on that for the exact reasons above (you can't predict when -and if- it will be called).
有一个finalize(继承的)方法,但由于上述确切原因,您不能依赖它(您无法预测何时 - 以及是否 - 会调用它)。
回答by Pierre
If you just need to cleanup some resources, you can call Runtime.getRuntime().addShutdownHook
如果只是需要清理一些资源,可以调用Runtime.getRuntime().addShutdownHook
回答by TofuBeer
Automatic object "destruction" in Java never happens at a guaranteed time. The only grantees for garbage collection are that before an object is collected the finalizer method will be called. Of course the garbage collector is never guaranteed to run, or do anything when it does run. So there is no guarantee that the finalize method will be called.
Java 中的自动对象“销毁”永远不会在有保证的时间发生。垃圾收集的唯一受助者是在收集对象之前将调用终结器方法。当然,垃圾收集器从不保证运行,或者在运行时做任何事情。所以不能保证会调用 finalize 方法。
If you want to simulate C++ destructors in Java the best way is to use the following idiom (there are variations when it comest to exception handling - I'll just show the simplest case here):
如果您想在 Java 中模拟 C++ 析构函数,最好的方法是使用以下习惯用法(在异常处理方面有多种变化 - 我将在这里仅展示最简单的情况):
final Resource r;
r = new Resource();
try
{
r.use();
}
finally
{
r.cleanup();
}
where the "cleanup" method is the "destructor".
其中“清理”方法是“析构函数”。
This is more like the C++ Resource Acquisition Is Initialization idiomwhich is really for stack based objects, but isn't as nice.
这更像是C++ Resource Acquisition Is Initialization 惯用语,它实际上适用于基于堆栈的对象,但不是那么好。
回答by pnt
You can check this for more info on finalization - finalize() method
您可以查看此以获取有关终结的更多信息 - finalize() 方法
回答by Enno Shioji
Since others are talking about normal cases.. There are special cases where you want to create destroy(), destruct(), releaseExternalResources(), shutdown()etc. methods that should be actively calledby the entity that controls the life cycle of that instance.
因为别人都在谈论正常情况。还有,你要创建的特殊情况下 destroy(),destruct(),releaseExternalResources(),shutdown()方法等应积极呼吁由实体控件实例的生命周期。
For example, an object can be an ActiveObject, which has live threads in it. In this case, you want to shut them down because else you will have memory leaks.
例如,一个对象可以是一个 ActiveObject,其中有活动线程。在这种情况下,您希望关闭它们,否则您将有内存泄漏。
While one may not call that a destructor...
虽然人们可能不会称其为析构函数......
On a sidenote, I guess that interview question was intended as a trick question!
在旁注中,我猜这个面试问题是一个技巧问题!
回答by Jefferey Cave
Try-with-resources is available as of Java 1.7
Try-with-resources 从 Java 1.7 开始可用
Anything that inherits from Closeableor Autocloseablecan use it.
任何继承自它Closeable或Autocloseable可以使用它的东西。
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
try (FileReader br = new FileReader(path)) {
return br.readLine();
}
This will automatically call a closefunction which is guaranteed to be called at the end of the block.
这将自动调用一个close函数,该函数保证在块的末尾被调用。

