In simplest form, following is the design:
class Session {
Timer t = new Timer();
// ...
};
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.
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)
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.
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.
How do you create a Session? If you do it within a try/catch block, you can clean up everything in a finally block.
I would write a close() method that took care of it and call it in a finally block.