Java中是否有等效的C ++析构函数? [英] Is there C++ destructor equivalent in Java?

查看:87
本文介绍了Java中是否有等效的C ++析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最简单的形式是以下设计:

In simplest form, following is the design:

class Session {
  Timer t = new Timer();
  // ...
};

每当分配 Session 时,我就开始里面的计时器;计时器将在10-20分钟后过期。现在,假设 Session 是否在计时器到期之前被销毁;那是我必须停止计时器的情况我不知道在 Session 被销毁时是否总是有最后一个方法被调用。

Whenever, Session is allocated, I start a timer inside it; the timer will be expired after 10-20 mins. Now, suppose if Session is destroyed before the timer can expire; then it's a scenario where I must stop timer. I don't know if is there any last method which is always called when Session is destroyed.

是否存在Java中某种等效的C ++析构函数,它可以帮助我在 Session 被销毁时使用 cancel()计时器吗? (无需等待GC)

Is there some sort of C++ destructor equivalent in Java, which help me to cancel() the timer when Session is destroyed ? (without waiting for GC)

编辑:请不要为C ++重新标记。我想要类似的东西。 会话是一个电话会话,当与它连接的所有用户断开连接时,该会话将被销毁。现在,没有最后调用的 Session 方法,也没有任何异常。

Edit: Please don't retag for C++. I wanted something of that equivalent. The Session is a phone session which is get destroyed when all the user connected to it are disconnected. Now, there is no Session method which is called lastly nor there is any exception.

推荐答案

不,Java中没有内置此类东西。最接近的是编写终结器,但不能保证它将运行。

No, there's no such thing built into Java. The closest is to write a finalizer, but there's no guarantee that it'll run.

会话如何销毁?如果有一种方法,一定要把代码放在那里。

How is a Session destroyed? If there's a method called, by all means put the code there.

如何创建会话?如果在try / catch块中执行此操作,则可以清除finally块中的所有内容。

How do you create a Session? If you do it within a try/catch block, you can clean up everything in a finally block.

我会编写一个close()方法来处理它,并在finally块中调用它。

I would write a close() method that took care of it and call it in a finally block.

这篇关于Java中是否有等效的C ++析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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