Wednesday, September 1, 2010

Deterministic lifetime of object in c++ as compared to java

C++ approach of Object Destruction

Some object-oriented programming languages, notably C++, have explicit destructor methods for any cleanup code that may be needed when an object is no longer used. The most common activity in a destructor is reclaiming the memory set aside for objects. Because Java does automatic garbage collection, manual memory reclamation is not needed and so Java does not support destructors.
Of course, some objects utilize a resource other than memory, such as a file or a handle to another object that uses system resources. In this case, it is important that the resource be reclaimed and recycled when it is no longer needed.
So cpp follows deterministic approach of object destruction.

Java Approach of object destruction

Java's approach is automatic garbage collection. You can add a finalize method to any class. The finalize method will be called before the garbage collector sweeps away the object. In practice, do not rely on the finalize method for recycling any resources that are in short supply—you simply cannot know when this method will be called. So java follows non-deterministic approach.

Advantage of Garbage collection

See here for advantage of garbage collection.

Disadvantage of Garbage collection

See here for disadvantage of Garbage collection

 

Final note

Garbage collection has increased problem, rather than solving many. Due to limited memory, we can get out of memory error. But this problem or disadvantage, we have to live with java.

No comments:

Post a Comment

Chitika