Is there a C ++ destructor equivalent in Java?

In the simplest form below is the design:

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

Whenever Session is highlighted, I start a timer in it; the timer will expire after 10-20 minutes. Now suppose that if Session destroyed before the timer expires; then this is the scenario where I have to stop the timer. I do not know if there is any last method that is always called when Session destroyed.

Is there any equivalent of a C ++ destructor in Java that helps me cancel() timer when destroying Session ? (no wait GC)

Change Please do not overwrite C ++. I wanted something like that. Session is a phone session that is destroyed when all users connected to it are disconnected. Now there is no Session method called last, and there is no exception.

+5
java destructor
source share
8 answers

No, there is no such thing built into Java. The closest thing is to write a finalizer, but there is no guarantee that it will work.

How is a session destroyed? If the method is called there, be sure to put the code there.

How do you create a session? If you do this in a try / catch block, you can clear everything in the finally block.

I would write a close () method that takes care of this and calls it in the finally block.

+6
source share

Unlike C ++, you cannot control the release of an object in Java, that is, the GC collects objects whenever it sees fit, simply ensuring that it will not collect everything that can be achieved using any link that is in the area at a given time.

There is Object.finalize() , which acts as the last chance to clear, but the runtime does not guarantee that it will be called at all.

I would review the design and try to come up with a clearer way to clear your timers.

+2
source share

In Java, variables do not directly represent objects similar to what they do in C ++ - variables in Java are references to objects. Thus, an object cannot go out of scope - only a variable related to an object can go out of scope.

You can override finalize (), which is a method of the Object class that is called by the garbage collector when it is about to finally drop the object, but this is not the same as the destructor. See the API documentation for the finalize () method in the Object class.

+2
source share

Only the first link suggested by stackoverflow

Is there a destructor for Java?

+1
source share

First, finalize not the equivalent of a destructor. Do not try to use it as one; it will not work. There is nothing for Java for Java, but in some circles there is an agreement to use void dispose() for this; instead of delete ptr; you write ptr.dispose() . (The memory, of course, will be fixed later.) In such cases, it is also good to define finalize to generate some internal error if the object is fixed before dispose .

+1
source share

In most cases, you can structure the problem, so you do not need a destructor.

Creating a timer for each session is relatively difficult. You better send a delay job to the ScheduledExecutorService. Having made light weight, it is not necessary to cancel it. (Actually cancel () does not delete it, it is marked as not running)

In this case, you can have a singleton ScheduledExecutorService for simplification.

 class Session { private static final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(); private Future<Void> timeoutFuture = null; // call every time you want the timeout to start from now. public void resetTimer() { if(timeoutFuture != null) timeoutFuture.cancel(false); timeoutFuture = timer.schedule(new Callable<Void>() { public Void call() { sessionTimedOut(); return null; } }, TIMEOUT_SECONDS, TimeUnit.SECONDS); } void sessionTimedOut() { // what to do when the session times out. } } 

Here's an expensive component, the ScheduledExecutorService is created once and lives on throughout the life of the application. The future is discarded when the session is cleared (and the task has expired)

+1
source share

There is no such method in java. The finalize() method, defined at the top level of Object , can be called when the object is destroyed by the garbage collector, but this is not a behavior you can rely on.

The best you can do is simply set the object to null (removes the link), which makes it ready to collect garbage.

0
source share

You can use CDI (Injection Dependency Injection) - for example, Weld or run the program on some JEE server (TomEE, JBoss, etc.). The following is an example of working with databases.

Use the appropriate @ ... Scoped annotation (ApplicationScoped, SessionScoped, etc.) in your class, as you prefer, for example:

 @ApplicationScoped public class MyDatabaseFactory implements Serializable {} 

Do what you would like to do in the constructor in some method annotated with @PostConstruct :

 @PostConstruct private void initializeObjectsOrConnections() { // ... } 

Add your object using the @Inject annotation to other places (if you want):

 public class MyApplication { @Inject MyDatabaseFactory databaseFactory; // ... } 

Clearing, destroying objects, and disconnecting from the database — what you wanted to do in the destructor from C ++ in the method annotated with the @PreDestroy class of the MyDatabaseFactory class, for example:

 @PreDestroy private void destroyObjectsOrCloseConnections() { // ... } 

It is very simple to use, and in Java we have the equivalent of a destructor from C ++.

0
source share

All Articles