Is There a Destructor for Java

Is there a destructor for Java?

Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.

There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error).

There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required...

How to define destructors?

In Java, there are no destructors but you can use method Object#finalize() as a work around.

The Java programming language does not guarantee which thread will
invoke the finalize method for any given object. It is guaranteed,
however, that the thread that invokes finalize will not be holding any
user-visible synchronization locks when finalize is invoked. If an
uncaught exception is thrown by the finalize method, the exception is
ignored and finalization of that object terminates.

class Book {
@Override
public void finalize() {
System.out.println("Book instance is getting destroyed");
}
}

class Demo {
public static void main(String[] args) {
new Book();//note, its not referred by variable
System.gc();//gc, won't run for such tiny object so forced clean-up
}
}

output:

Book instance is getting destroyed

System.gc()

Runs the garbage collector. Calling the gc method suggests that the
Java Virtual Machine expend effort toward recycling unused objects in
order to make the memory they currently occupy available for quick
reuse. When control returns from the method call, the Java Virtual
Machine has made a best effort to reclaim space from all discarded
objects.

The call System.gc() is effectively equivalent to the call:

Runtime.getRuntime().gc()

Object#finalize()

Called by the garbage collector on an object when garbage collection
determines that there are no more references to the object. A subclass
overrides the finalize method to dispose of system resources or to
perform other cleanup.

Call destructor on close objects

There is no destructors in java

class Tralala(){ 

int i=0;

Tralala(){
i=i+1;}

protected void reset( ){
i=i-1;
}}

call reset method when ever you want to destruct.

As a side note:There are lots of corrections in your code like naming conventions, formatting and also providing modifiers.

And I'm not getting, when finalize called, your instance is no more. Why you are resetting at that time,Since after that NO MORE OPERATIONS ON THAT OBJECT.

Is there C++ destructor equivalent in 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.

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.

Deconstructor in Java?

Dear AnkitNeo you have given the answer yourself.

By setting the variable to null and calling

System.gc();

you will free up the memory. However, it is not guaranteed that System.gc() will actually garbage collect. According to this post: When does System.gc() do anything most of the time the system will garbage collect. I believe it will just not GC if there is currently a very high CPU load.

java class destroy's another class

Now I need to destroy the "Shepherd" class to end the agent and then start a new game. I know that java classes has destructors.

You have misunderstood something fairly fundamental:

  1. Java doesn't have destructors. You might be confusing destructors with finalizers. These are methods that are called after the GC has decided to delete an object. (This is an oversimplification ... but the real point is that finalizers are not relevant to this problem. In fact, there very few cases where finalizers are relevant.)

  2. You can't destroy objects. Objects are destroyed by the garbage collector when they are no longer needed. More specifically, they are destroyed when they are unreachable; i.e. when they can no longer influence the execution of the program.

So what do you do?

First of all, forget about "destroying" objects. Instead think about how to prepare for the next game. There are two approaches.

  1. You could implement a reset() or similar method on all "game" objects that need to be reset / reinitialized when your start a new game.

  2. You could simply drop all of the relevant "game" object on the floor and create new ones. (The GC will take care of the garbage.)

Or you could use a combination of the two approaches; e.g. reset the Pasture object to its initial state and discard / recreate the Shepard, Sheep and so on.

Destructors in C++ (Compared to java)

C++ is very different than Java in this area, so here's a brief overview:

allocation: memory is set aside for an object.

construction: The object is prepared to be used.

destruction: The object "finishes" everything and disassembles itself.

deallocation: the memory is given back to the system.

int main() {
int myint; //automatic int object is allocated and constructed
//stuff
} // when main ends, automatic int object is destroyed and deallocated

int main() {
int* mypointer; //automatic pointer object is allocated and constructed
mypointer = new int; //dynamic int object is allocated and constructed
//stuff
delete mypointer; //dynamic int object is destroyed and deallocated
} // when main ends, automatic pointer object is destroyed and deallocated
// note: Pointers to _not_ delete the object they point to.

class myclass {
//members
public:
myclass() {} //this is the default constructor
myclass(const myclass& rhs) {} //this is the copy constructor
myclass& operator=(const myclass& rhs) {return *this} //this is the assignment operator
~myclass() {} //this is the destructor
};

When a function ends, all the variables in the function itself (which we call automatic) have their destructors called, and then they are deallocated automatically. This means for objects local to a function, they automatically clean themselves the instant the function ends. This also applies magically to members of a class. When it is destroyed, each of it's members will automatically be destroyed. This means most destructors are empty.

If you allocate stuff manually (with the new keyword), it must be destroyed and deallocated manually with the delete keyword. When you call delete, it will destroy (and deallocate) right there and then, and won't continue until it is done. If you forget, it WILL NOT EVER GET DEALLOCATED (altough, some operating systems will deallocate it when your program ends).

Since people make mistakes, the "correct" thing to do when you need dynamic objects is:

int main() {
std::unique_ptr<myclass> myptr = new myclass(); //allocate and construct
} //both the unique_ptr and the dynamic object are destroyed and deallocated

and the unique_ptr is smart enough to automatically clean up the thing it points at, freeing you for bigger concerns.

The reason C++ does this is because if you have a object F that represents that file, it might have a exclusive lock on that file. In C++, once F is destroyed, you can immediately create an object G that uses that same file. In Java, there's no guarantee that the finalizer will ever run, meaning that file may remain locked until your program ends. (Unlikely, but possible)



Related Topics



Leave a reply



Submit