Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Java Garbage Collection and destructors

  1. #1
    Junior Member
    Join Date
    Sep 2009
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Red face Java Garbage Collection and destructors

    I am asked several times there two questions in interviews and I need a good answer to give for it if I am asked it in my next interview.

    1. What is Garbage Collection in java? how it works in java?

    2. Why there is no concept of destructors (like in c++) in java?

    Please suggest some good answer to give for these questions at the time of interviews.

    Thanks in advance.


  2. #2
    Junior Member
    Join Date
    Sep 2009
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java Garbage Collection and destructors

    I'm no expert, but I've read a little about this: I've never heard of destructors (I don't know c++), and java doesn't need them simply because garbage collection is automated. As to the "what is garbage collection", it's simply throwing out the trash.

    Say you have in your main method, <int taxes = 15>, you carry it over to another method but want a percent instead you might declare a variable <double exactTaxes = 0.15>, and then from then on, you refer only to the exactTaxes variable, and no longer need the Integer taxes.

    Java would pick up on this, and throw out that Integer as it no longer needs to take up any resources. Hope this helps!

  3. #3
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Java Garbage Collection and destructors

    1. Garbage Collector
    Garbage collection is a way for the JVM to clean the heap. The heap is where all referenced objects live. Primitives like int and double aren't really objects in the same way as types so therefore they aren't garbage collected. There is no definite answer to how the garbage collector works.

    If you wish to read up on the memory mangement in Java, have a look at http://java.sun.com/j2se/reference/w...whitepaper.pdf

    Here is an extract from The Java Language Environment

    2.1.6 Memory Management and Garbage Collection
    C and C++ programmers are by now accustomed to the problems of explicitly managing memory: allocating memory, freeing memory, and keeping track of what memory can be freed when. Explicit memory management has proved to be a fruitful source of bugs, crashes, memory leaks, and poor performance.
    Java technology completely removes the memory management load from the programmer. C-style pointers, pointer arithmetic, malloc, and free do not exist. Automatic garbage collection is an integral part of Java and its run-time system. While Java technology has a new operator to allocate memory for objects, there is no explicit free function. Once you have allocated an object, the run-time system keeps track of the object's status and automatically reclaims memory when objects are no longer in use, freeing memory for future use.

    Java technology's memory management model is based on objects and references to objects. Java technology has no pointers. Instead, all references to allocated storage, which in practice means all references to an object, are through symbolic "handles". The Java technology memory manager keeps track of references to objects. When an object has no more references, the object is a candidate for garbage collection.

    Java technology's memory allocation model and automatic garbage collection make your programming task easier, eliminate entire classes of bugs, and in general provide better performance than you'd obtain through explicit memory management. Here's a code fragment that illustrates when garbage collection happens:

     class ReverseString {
        public static String reverseIt(String source) {
            int i, len = source.length();
            StringBuffer dest = new StringBuffer(len);
     
            for (i = (len - 1); i >= 0; i--) {
                dest.appendChar(source.charAt(i));
            }
            return dest.toString();
        }
    }

    The variable dest is used as a temporary object reference during execution of the reverseIt method. When dest goes out of scope (the reverseIt method returns), the reference to that object has gone away and it's then a candidate for garbage collection.

    2.1.7 The Background Garbage Collector
    The Java technology garbage collector achieves high performance by taking advantage of the nature of a user's behavior when interacting with software applications such as the HotJavaTM browser. The typical user of the typical interactive application has many natural pauses where they're contemplating the scene in front of them or thinking of what to do next. The Java run-time system takes advantage of these idle periods and runs the garbage collector in a low priority thread when no other threads are competing for CPU cycles. The garbage collector gathers and compacts unused memory, increasing the probability that adequate memory resources are available when needed during periods of heavy interactive use.
    This use of a thread to run the garbage collector is just one of many examples of the synergy one obtains from Java technology's integrated multithreading capabilities--an otherwise intractable problem is solved in a simple and elegant fashion.

    2. Destructors
    Surprise perhaps but there is sort of a concept of destructors in Java and its a method which every object inherits from the class Object. The method is called finalize() and is run only once by the garbage collector before it cleans up the object. There is no real reason to clean up all your objects using this method though because the garbage collector will automatically clean up any other objects that become unreferenced as the first object gets cleaned up.

    Here is an override of the finalize mehotd.

        @Override
        protected void finalize() throws Throwable {
            super.finalize();
        }

    For some more information on finalize and garbage collection have a look at Java Programmer's SourceBook : Thinking in Java

    // Json
    Last edited by Json; September 30th, 2009 at 03:11 AM.

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Java Garbage Collection and destructors

    Ahh, good old C++.

    Yes, destructors are useless in Java because in Java you don't need to explicitly tell the computer you're done with a bit of memory when it goes out of scope. Java's Garbage Collector takes care of any memory release that was allocated by your program.

    A visualization of this concept is this:

    Say you're using some tools. In both C++ and Java, every time you create an object is analogous to getting a new tool. The garbage collector in Java can be viewed as the Professor in the lab who occasionally comes around, picking up the tools no one's using and returning them to the tool closet. However, C++ doesn't have this person coming around cleaning up the workshop, so you must put it back yourself (the destructor). If you don't, the tool will continue to sit on the workbench, so when someone wants to use that tool and goes to look for it in the tool closet, it isn't there.

    Note this, though: The professor will always pick up tools he thinks no one is using, and he's quick about it. As soon as you set the tool down, he picks it up and returns it to the tool closet. In Java, this is similar to an object becoming un-referenced. The garbage collector sees that the object has no one pointing to it for use, and instantly reclaims the memory. Exactly how this is implemented on a low level is beyond my knowledge, and I think it still might be proprietary information, or it could have been released as open source with the OpenJDK project.

  5. #5
    Junior Member
    Join Date
    Sep 2009
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Smile Re: Java Garbage Collection and destructors

    Thank you all of you. It really helps me a lot.

    Also Thanks Json for the weblink. It has everything I needed. Thanks.

  6. #6
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Java Garbage Collection and destructors

    No worries, please marked the thread as SOLVED if you are happy with the answers provided.

    Happy coding!

    // Json

Similar Threads

  1. Garbage Collection?
    By kalees in forum Collections and Generics
    Replies: 6
    Last Post: September 23rd, 2009, 03:07 AM

Tags for this Thread