What is difference between final,finally and finalize?

Why is there no destructor in Java and what's the difference between finalize() and destructor?

  • I know there's a garbage collector in Java which does the removal of objects, but what's the need for a garbage collector when we can simply have destructors?

  • Answer:

    Because we (programmers) aren't very good at managing references to objects or allocated memory. In systems of any complexity, it is very easy to deallocate a chunk of memory leaving some other pointer to it. Tracking down bugs from invalid pointers is a leading cause of hair loss.

Andrew Warinner at Quora Visit the source

Was this solution helpful to you?

Other answers

Java and C++ have very different philosophies about resource management. In C++, resource management is explicit, and deliberate. This originated as an extension of the memory management patterns of C: malloc memory when you need it, free it when you are done. If this were all that it had remained, the difference between the two could be summed up as follows: Java exchanges an occasional slowdown as GC is performed (and not that bad a slowdown on modern JIT-based VMs) for far fewer program errors due to double deletes or memory leaks. As it turns out, however, C++ evolved into a language wholly unlike C (a fact that I have been attempting to hammer, without much success, into the heads of some of my colleagues) in which the operative paradigms utilize stack unwinding and scope control in ways that the original design of the language did not entirely foresee. To a highly skilled C++ programmer, the stack is the point of greatest control. Here, you can guarantee the correct cleanup of not just memory, but locks, file handles, sessions, and transactions. Let's look at a practical example: in C++, a database operation can be written so that it will be rolled back if it doesn't successfully commit - without additional programmer effort overhead. Java has no such intrinsic mechanism. It has the "finally" construct on exceptions, but beyond that, the best practice is to explicitly release non-memory resources before exiting the function that acquired them. Java's "finalize()" does not encompass all that a destructor does. It does allow non-memory resources to be cleaned up as a last ditch solution, but it doesn't provide order guarantees, and the dependency guarantees are (marginally) more fragile than stack based cleanup. The C++ standard library does acknowledge the value of unowned (shared) resources, and, in deference to the lack of GC (I'm not going to count the C++11 GC allowance as support) does provide some very well engineered smart pointers. Using shared_ptr, and breaking cyclic dependencies with weak_ptr, a great number of situations where GC would have been essential are circumvented. However useful these provisions in C++ are, the simple truth is, Java is a more approachable language for a programmer who does not wish to spend time focusing on questions of ownership or resource management. Now, even more than C, C++ is a language for heavy hitters, deep dwellers, nerds' nerds, alpha geeks. Even as the new standard simplifies its semantics in many places, it introduces heavier constructs for performance optimization and resource management. Rvalue references and move semantics allow for perfect forwarding, and lamdas and auto allow capture by reference, and this allows the compiler to elide local code blocks into non-local algorithms... and you need to understand these things, at a fundamental level, to take advantage of their performance optimizations. With Java, you can be a pretty good programmer without understanding anything beyond business logic, and most of the time, making decisions for optimization actually ends up getting in the JIT compiler's way, rather than improving performance. Look at it like this: if you're writing Java, don't try to write C++. And if you're writing C++, FFS, don't try to make it into a semi-neutered dialect of Java or an extended dialect of C. (I'm looking at a lot of people with this one...)

Nathan F Yospe

Programmers know about the importance of initialization, but often forget the importance of cleanup. After all, who needs to clean up an int? But with libraries, simply “letting go” of an object once you’re done with it is not always safe. Of course, Java has the garbage collector to reclaim the memory of objects that are no longer used. Now consider an unusual case: Suppose your object allocates “special” memory without using new. The garbage collector only knows how to release memory allocated with new, so it won’t know how to release the object’s “special” memory. To handle this case, Java provides a method called finalize( ) that you can define for your class. Here’s how it’s supposed to work. When the garbage collector is ready to release the storage used for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the object’s memory. So if you choose to use finalize( ), it gives you the ability to perform some important cleanup at the time of garbage collection. This is a potential programming pitfall because some programmers, especially C++ programmers, might initially mistake finalize( ) for the destructor in C++, which is a function that is always called when an object is destroyed. It is important to distinguish between C++ and Java here, because in C++, objects always get destroyed (in a bug-free program), whereas in Java, objects do not always get garbage collected. Or, put another way: 1. Your objects might not get garbage collected. 2. Garbage collection is not destruction. If you remember this, you will stay out of trouble. What it means is that if there is some activity that must be performed before you no longer need an object, you must perform that activity yourself. Java has no destructor or similar concept, so you must create an ordinary method to perform this cleanup. For example, suppose that in the process of creating your object, it draws itself on the screen. If you don’t explicitly erase its image from the screen, it might never get cleaned up. If you put some kind of erasing functionality inside finalize( ), then if an object is garbage collected and finalize( ) is called (and there’s no guarantee this will happen), then the image will first be removed from the screen, but if it isn’t, the image will remain. That is, the sole reason for the existence of the garbage collector is to recover memory that your program is no longer using. So any activity that is associated with garbage collection, most notably your finalize( ) method, must also be only about memory and its deallocation. Does this mean that if your object contains other objects, finalize( ) should explicitly release those objects? Well, no—the garbage collector takes care of the release of all object memory regardless of how the object is created. It turns out that the need for finalize( ) is limited to special cases in which your object can allocate storage in some way other than creating an object. But, you might observe, everything in Java is an object, so how can this be? It would seem that finalize( ) is in place because of the possibility that you’ll do something Clike by allocating memory using a mechanism other than the normal one in Java. This can happen primarily through native methods, which are a way to call non-Java code from Java.  C and C++ are the only languages currently supported by native methods, but since they can call subprograms in other languages, you can effectively call anything. Inside the non-Java code, C’s malloc( ) family of functions might be called to allocate storage, and unless you call free( ), that storage will not be released, causing a memory leak. Of course, free( ) is a C and C++ function, so you’d need to call it in a native method inside your finalize( ).

Devanshu Dwivedi

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.