C++ Destructors Versus Java Finalization

By: Emiley J Emailed: 1674 times Printed: 2153 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

When you move from C++ to Java, one of the more subtle, yet important issues you will face is the difference between a C++ destructor and a Java finalize() method. Although similar in many respects, their actual operation is distinctively different. Let's begin by reviewing the purpose and effect of a C++ destructor and the Java finalize() method. In C++, when an object goes out of scope, it is destroyed. Just prior to its destruction, its destructor function is called (if it has one). This is a hard-and-fast rule. There are no exceptions. Let's look more closely at each part of this rule:
  1. Every object is destroyed when it goes out of scope. Thus, if you declare a local object inside a function, when that function returns, that local object is automatically destroyed. The same goes for function parameters and for objects returned by functions.
  2. Just before destruction, the object's destructor is called. This happens immediately, and before any other program statements will execute. Thus, a C++ destructor will always execute in a deterministic fashion. You can always know when and where a destructor will be executed.

In Java, the tight linkage of the destruction of an object and the calling of its finalize() method does not exist. In Java, objects are not explicitly destroyed when they go out of scope. Rather, an object is marked as unused when there are no longer any references pointing to it. Even then, the finalize() method will not be called until the garbage collector runs. Thus, you cannot know precisely when or where a call to finalize( ) will occur. Even if you execute a call to gc( ) (the garbage collector), there is no guarantee that finalize( ) will immediately be executed.

While the deterministic behavior of a C++ constructor and the somewhat probabilistic aspect of finalization are of little concern in most cases, they will have an impact on others. For example, consider the following C++ program:

// This C++ program can call f() indefinitely.
#include <iostream>
#include <cstdlib>
using namespace std;
const int MAX = 5;
 

int count = 0;
class X {
public:
// constructor
X() {
if(count<MAX) {
count++;
}
else {
cout << "Error — can't construct";
exit(1);
}
}
// destructor
~X() {
count—;
}
};
void f()
{
X ob; // allocate an object
// destruct on way out
}
int main()
{
int i;
for(i=0; i < (MAX*2); i++) {
f();
cout << "Current count is: " << count << endl;
}
return 0;
}

Here is the output generated by this program:

Current count is: 0
Current count is: 0
Current count is: 0
Current count is: 0
Current count is: 0
Current count is: 0
Current count is: 0
Current count is: 0
Current count is: 0
Current count is: 0

Look carefully at the constructor and destructor for X. The constructor increments the value of count as long as count is less than MAX. The destructor decrements count. Thus, count is incremented when an X object is created and decremented when an X object is destroyed. But no more than MAX objects can exist at any one time. However, in main( ), f( ) is called MAX*2 times without causing an error! Here is why. Inside f( ), an object of type X is created, causing count to be incremented, and then the function returns. This causes the object to immediately go out of scope and its destructor to be called, which decrements count. Thus, calling f( ) has no net effect on the value of count. This means that it can be called indefinitely. However, this is not the case when this program is converted to Java.
 

Here is the Java version of the preceding program:

// This Java program will fail after 5 calls to f().
class X {
static final int MAX = 5;
static int count = 0;
// constructor
X() {
if(count<MAX) {
count++;
}
else {
System.out.println("Error — can't construct");
System.exit(1);
}
}
// finalization
protected void finalize() {
count—;
}
static void f()
{
X ob = new X(); // allocate an object
// destruct on way out
}
public static void main(String args[]) {
int i;
for(i=0; i < (MAX*2); i++) {
f();
System.out.println("Current count is: " + count);
}
}
}

This program will fail after five calls to f( ), as this output shows:

Current count is: 1
Current count is: 2
Current count is: 3
Current count is: 4
Current count is: 5
Error — can't construct

The reason the program fails is that garbage collection does not occur each time f( ) returns. Thus, finalize( ) is not invoked, and the value of count is not decremented. After five calls to the method, count reaches its maximum value and the program fails. It is important to emphasize that precisely when garbage collection occurs is implementation dependent. It is possible that for some implementation of Java, on some platform, the preceding program will function similarly to its C++ version. However, the point of the example remains: In C++, you know when and where a destructor will be called. In Java, you do not know when or where finalize( ) will be executed. Therefore, when porting code from C++ to Java, you will need to watch for instances in which the precise timing of the execution of a destructor is relied upon.


C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

"This happens immediately, and before any other program statements will execute. Thus, a C++ destructor will always execute in a deterministic fashion. You can always know when and where a destructor will be executed. "

Are you sure about this??? Then there must have been a change in the language. "The C++ Programming Language by Bjarne Struostrup" (granted, not the C++ standard) says in r.12.2 "The exact point of destruction is implementation dependent." Some compilers I've used do in fact destroy temporaries and automatic variables immediately; but other compilers I have used do not. It's REALLY annoying not being able to treat destructors as deterministic. If the language DOES IN FACT define the point of destruction, then I'm writing to my compiler vendors! Please give us a paragraph reference for this behavior.


View Tutorial          By: David at 2007-10-02 06:52:20

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Emiley J
Password must include both numeric and alphabetic characters - Magento
What is Hadoop?
Returning multiple values from a web service
Tomcat and httpd configured in port 8080 and 80
Java Webservices using Netbeans and Tomcat
Java WebService connected to Database
How to Deploy a Java Web Service
Call a webservice in Java
Java WebService - Create your first web service in Java
package javax.jws does not exist
Getting Started with Android
HTML5 Location - getCurrentPosition() in HTML5
HTML5 Canvas - Using Canvas in HTML5
HTML5 - Introduction
HTML5 Video - Handling video in HTML5

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Using Comments in a C++ Program
The indirection operator (*) - dereference operator.
Dot (.) vs Arrow (->) to access data members in C++
Using peek() and putback() with cin in C++
virtual inheritance example in C++
Function overloading in C++
Checking Prime Number in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
What Is a Pointer in C++?
C++ Sample Program for Allocating, using, and deleting pointers.
this Pointer in C++
C ++ Reference Parameters Versus Java Reference Parameters
Converting C++ Multiple-Inheritance Hierarchies to Java
C++ Destructors Versus Java Finalization
Most Emailed Articles (in C++)
Looping with the keyword goto in C++
Default arguments in C++
Compiling and Linking Multiple Source Files in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Tutorial on Classes and Members in C++
for Loops in C++
Using switch Statements in C++
Operator Precedence in C++
How to handle Exceptions in C++
strcpy() and strncpy() sample program in C++
assert() example program in C++
Using peek() and putback() with cin in C++
Function overloading in C++
File in C++ - Writing text to a file in C++
Pass by Reference vs Pass Value in C++ functions