Object finalize method

As far as my concept goes, the finalize() method for an object can be called only once. If it is called explicitly, the garbage collector will not call it again. But one of my programs is calling finalize() method apprantly more than once. Please see the code below.
class ObjFinalizeTest{
     public void finalize() {
          System.out.println("Class Terminated");
     static void foo() {
          ObjFinalizeTest aa = new ObjFinalizeTest();
public class Chap1 {
     static char a ;
     static int b ;
     static ObjFinalizeTest c;
     public static void main(String[] args) {
          c= new ObjFinalizeTest();
          c.finalize(); //explicit call to finalize
          System.out.println(c);
          c=null;
          System.gc();
}this is the output I am getting
Class Terminated
ObjFinalizeTest@923e30
Class TerminatedCan anybody please explain this phenomenon

Finalize is just like any other method, it's nothing special, same with main. What you are doing is explicitly calling it and then the JVM is calling it as well. I think the docs only state that the JVM will only call the method once, you however can call it as many times as you like.

Similar Messages

  • Finalize() method being called multiple times for same object?

    I got a dilly of a pickle here.
    Looks like according to the Tomcat output log file that the finalize method of class User is being called MANY more times than is being constructed.
    Here is the User class:
    package com.db.multi;
    import java.io.*;
    import com.db.ui.*;
    import java.util.*;
    * @author DBriscoe
    public class User implements Serializable {
        private String userName = null;
        private int score = 0;
        private SocketImage img = null;
        private boolean gflag = false;
        private Calendar timeStamp = Calendar.getInstance();
        private static int counter = 0;
        /** Creates a new instance of User */
        public User() { counter++;     
        public User(String userName) {
            this.userName = userName;
            counter++;
        public void setGflag(boolean gflag) {
            this.gflag = gflag;
        public boolean getGflag() {
            return gflag;
        public void setScore(int score) {
            this.score = score;
        public int getScore() {
            return score;
        public void setUserName(String userName) {
            this.userName = userName;
        public String getUserName() {
            return userName;
        public void setImage(SocketImage img) {
            this.img = img;
        public SocketImage getImage() {
            return img;
        public void setTimeStamp(Calendar c) {
            this.timeStamp = c;
        public Calendar getTimeStamp() {
            return this.timeStamp;
        public boolean equals(Object obj) {
            try {
                if (obj instanceof User) {
                    User comp = (User)obj;
                    return comp.getUserName().equals(userName);
                } else {
                    return false;
            } catch (NullPointerException npe) {
                return false;
        public void finalize() {
            if (userName != null && !userName.startsWith("OUTOFDATE"))
                System.out.println("User " + userName + " destroyed. " + counter);
        }As you can see...
    Every time a User object is created, a static counter variable is incremented and then when an object is destroyed it appends the current value of that static member to the Tomcat log file (via System.out.println being executed on server side).
    Below is the log file from an example run in my webapp.
    Dustin
    User Queue Empty, Adding User: com.db.multi.User@1a5af9f
    User Dustin destroyed. 0
    User Dustin destroyed. 0
    User Dustin destroyed. 0
    User Dustin destroyed. 0
    User Dustin destroyed. 0
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 1
    User Dustin destroyed. 1
    User Dustin destroyed. 1
    User Dustin destroyed. 1
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    User Dustin destroyed. 2
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    User Dustin destroyed. 3
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    User Dustin destroyed. 4
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    User Dustin destroyed. 5
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    User Dustin destroyed. 6
    Joe
    USER QUEUE: false
    INSIDE METHOD: false
    AFTER METHOD: false
    User Dustin pulled from Queue, Game created: Joe
    User Already Placed: Dustin with Joe
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    User Dustin destroyed. 7
    INSIDE METHOD: false
    INSIDE METHOD: false
    USER QUEUE: true
    INSIDE METHOD: false
    INSIDE METHOD: false
    User Dustin destroyed. 9
    User Joe destroyed. 9
    User Dustin destroyed. 9
    User Dustin destroyed. 9
    User Dustin destroyed. 9
    User Dustin destroyed. 9
    INSIDE METHOD: true
    INSIDE METHOD: false
    USER QUEUE: true
    INSIDE METHOD: false
    INSIDE METHOD: false
    INSIDE METHOD: true
    INSIDE METHOD: false
    USER QUEUE: true
    INSIDE METHOD: false
    INSIDE METHOD: false
    It really does seem to me like finalize is being called multiple times for the same object.
    That number should incremement for every instantiated User, and finalize can only be called once for each User object.
    I thought this was impossible?
    Any help is appreciated!

    Thanks...
    I am already thinking of ideas to limit the number of threads.
    Unfortunately there are two threads of execution in the servlet handler, one handles requests and the other parses the collection of User objects to check for out of date timestamps, and then eliminates them if they are out of date.
    The collection parsing thread is currently a javax.swing.Timer thread (Bad design I know...) so I believe that I can routinely check for timestamps in another way and fix that problem.
    Just found out too that Tomcat was throwing me a ConcurrentModificationException as well, which may help explain the slew of mysterious behavior from my servlet!
    The Timer thread has to go. I got to think of a better way to routinely weed out User objects from the collection.
    Or perhaps, maybe I can attempt to make it thread safe???
    Eg. make my User collection volatile?
    Any opinions on the best approach are well appreciated.

  • Help needed in overriding the finalize() method!

    Hi
    I need some help in overwriting the finalize() method.
    I have a program, but at certain points, i would like to "kill" a particular object.
    I figured that the only way to do that is to make that object's class override the finalize method, and call it when i need to kill the object.
    Once that is done, i would call the garbage collector gc() to hopefully dispose of it.
    Please assist me?
    Thanks
    Regards

    To, as you put it, kill an object, just null it. This
    will be an indication for the garbage collector to
    collect the object. In the finalizer, you marely null
    all fields in the class. Like this:
    public class DummyClass
    String string = "This is a string";
    Object object = new Boolean(true);
    public void finalize() throws Throwable
    super.finalize();
    string = null;
    object = null;
    public static void main(String[] args)
    //Create a new object, i.e allocate an
    te an instance.
    DummyClass cls = new DummyClass();
    //Null the reference
    cls = null;
    This is a pointless exercise. If an object is being finalized, then all the references it contains are about to cease being relevant anyway, so there's no purpose to be served in setting them to null.
    All that clearing a reference to an object does is to clear the reference. Whether the object is subsequently finalized depends on whether the object has become unreachable.
    Directly calling finalize is permitted, but doesn't usually serve any purpose. In particular, it does not cause the object to be released. Further, calling the finalize method does not consitute finalization of the object. Finalization occurs when the method is called as a consequence of a garbage collector action.
    If a variable contains a reference to an object (say a table), and you want a new table instead, then create a new table object, and assign its reference to the variable. Assuming that the variable was the only place that the old table's reference was stored, the old table will, sooner or later, get finalized and collected.
    Sylvia.

  • Finalize method is not working

    class Abc
         protected void finalize() throws Throwable
              System.out.println("Inside finalize");
            super.finalize();
    public class Finalize1
         public static void main(String args[])
              Abc a=new Abc();
              System.gc();
    }"Inside finalize" inside the finalize method is not getting printed.When the code ends won't the objects get garbage collected when the program ends.So shouldn't that statement get printed?

    a=null will workAs the API for System.gc() states:
    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.
    Note the language: "suggests", "a best effort". This is not the same as a guarantee that the object will be collected and its finalize run.

  • How the protected finalize method is called by garbage collector

    Dear All,
    I have a double regarding the calling mechanism of finalize method. The access specifier of finalize method is protected, not only that if a class overrides this method then also the finalize method can be protected in the subclass of Object. But the concept of protected access specifier is, from outside of the package it can be accessed only from subclass.
    The program (may be part of Garbage collector), which calls this (finalize) method mast not be in the same package (that is java.jang) nor it is a subclass of the class (whose finalize method it calls).
    Then how the finalize method is getting called by the garbage collector when it is protected?
    Regards,
    Gourab

    Refer to following link for the details
    http://www.me.umn.edu/~shivane/blogs/cafefeed/2005/09/why-is-finalize-method-protected.html
    The link gives answer to how a protected/private members are accessible to JVM or GC and why finalize is declared protected.

  • What happens when an exception occurs at finalize method ?

    What happens when an exception occurs at the time of cleaning objects in finalize methods?
    Will program crashes?

    1.) Why don't you try it? You can simply throw your own exception.
    2.) For this kind of questions the JVM specification is a good resource, for your concrete problem the chapter about finalization might be interested (look for the sentence starting with "If an uncaught exception ...").

  • Problem about finalize() method

    when will the finalize() execute?At the time the associated object is no longer available or at the time the next garbage collection happen ?
    When problem with jdbc,I must use connection in the object.And I want to release the connection at the moment the object disposed(no longer available).Can finalize method do this,if can not ,Any other method?

    finalize() is called when the garbage collector is collecting the object. see http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html#44748

  • Java API - finalize method for XmlResults

    Hello!
    I'm wondering why in DB XML Java code we have a finalize() method which invokes delete() method whereas we are supposed to invoke delete() method manually (according to the documentation). Is it ok if delete() method is invoked twice (it happens in case GC cleans up the XmlResults object) ? Can't we get some problems because of that?
    Thanks,
    Vyacheslav

    Also you should note that Java actually makes no guarantees that the finalize() method is called, and it can frequently happen in practice that this is the case. For instance, the JVM usually doesn't bother calling finalize() on objects if it is shutting down, which can be disastrous for DB XML objects like Environment, XmlManager and XmlContainer, which need to clean up and write data to disk when they are closed. Read the [FAQ | http://www.oracle.com/technology/products/berkeley-db/faq/xml_faq.html#16] for more details.
    John

  • Can anybody post me simple programme of finalize() method ?

    i have read as theoretically what is garbage collection and using finalize() method one can achieve but as a student i want to know simple program like we had destructor in c++
    thank you

    The finalize() method is described in the Object's API documentation.
    http://java.sun.com/javase/6/docs/api/java/lang/Object.html
    What is noticable from that description is how few guarantees the method makes. My advice would be don't use it.
    In particular if you try and use finalize() to clean up resources you will face a couple of problems:
    (1) Garbage collection might not ever run.
    (2) Across multiple objects, finalize order is not predictable.
    A better technique for dealing with the "resources" problem - using the finally keyword and an explicit close() method is described here:
    http://java.sun.com/developer/TechTips/2000/tt0124.html

  • Finalize() method for newer JVMs

    Hi,
    Just a quick question on finalize() if that's ok. From memory the only time the developer should have to implement this method is when you want to do something with a system resource during garbage collection.
    A finalize method should never have to worry about clearing object references etc? Correct?
    I am 99.9999999999% sure on this.
    I am looking at some old code here which contains some objects which implement the finalise method, I am trying to figure out why they did it.
    Is there any obscure case (i.e. with weak references or something) where an object may have to clear object references in finalise?
    Thanks in advance.

    malcolmmc wrote:
    beginner2 wrote:
    Hi,
    Just a quick question on finalize() if that's ok. From memory the only time the developer should have to implement this method is when you want to do something with a system resource during garbage collection.
    Even where you do want to do that (and it's rarely a good strategy except as some kind of backstop, since there's no guarantee you system resource related object will ever be garbage collected), I'd recommend using a PhantomReference instead. It's more controllable. You control what thread it's cleaned up on, you can pass references in a way that's dangerous in a finalize and you can discard it if (as should happen) the program explicitly closes it's connection with the resource.++agree: PhantomReference<TollBooth>

  • Finalize method, please, help

    I'm using jdk 1.4.2.08
    I have redefined the finalize method in my classes and simply i put a system.out
    just to see if vm calls for it or not.
    For some classes I see the messages in output console, for others not.
    The curious thing is that I use two profiles tools that allows to force garbage
    collector (pushing a toolbar button); after that I push the button the instance counts for ALL objects goes to zero.
    Teorically all instances of my classes has been destroyed;
    in other words both two profilers tells me that there are no dirty
    references (or memory leak)
    .... BUT.....
    no messages (for some classes) in output console are shown.
    Any ideas?
    Thanks.

    OK, I know that, but I force the GC using the profiler
    and after this the profiler shows in his monitor that all
    instance count of my classes is zero.
    But, for some of my classes, I dont't see in putput console
    the message given by a System.out placed in Finalized custom
    method.
    If this that is strange: for profiler all instances has been destroyed
    by GC, but java seems that does not calls finalized method......

  • How actually finalize() method works?

    Hi,
    [b]
    When the finalize method is called by GC or not? I made some simple test, please have a look at this code:
    package finalizetest;
    * @author krzys
    public class Test {
        /** Creates a new instance of Test */
        public Test() {
        public void finalize() {
            System.out.println("finalize...");
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            Test test = new Test();
            test = null;
            System.gc(); //when calling of GC is commented, then finalize doesn't work
    }If the System.gc() is called then finalize is invoked, if the line is ommited, then happens nothing
    How it works?
    Krzysztof

    There's no guarantee that finalize() will be called, ever. Don't explicitly call GC either - that's just setting yourself up for a bad design.
    finalize() is just a last-ditch effort to cleanup in case the user of your object didn't explicitly tell it to cleanup. If an object needs to do cleanup work when not in use, then create a method to do that. For example, I/O streams have a close() method and require that it get called, especially if the stream is attached to an actual file handle.

  • More than one entity found for a single-object find method

    Hi everyone...
    I have this error when my webservice is running..I don't know what it means and what would be the best solution..
    <pns:message>More than one entity found for a single-object find method.</pns:message>
    it throws an Exception..
    Thanks!

    = More than one row found in a DB with the "unique" key supplied...
    Your method is returning an object where it should return a collection ?
    Enjoy

  • Need to Hide Objects Default method in Approval Task

    Dear All,
      I have a requirement, where I need to hide the default method that is getting displayed in the approval task of the workflow.
    The employee object and Trip objects default method are getting displayed in the preview of approval task. And same is getting displayed in the universal worklist in the columns of attachments.
      There is an option in univesal worklist configuration where we can remove the attachments for display.
      But to our requirement , only certain objects and attachments should be shown in portal and R/3 of the approval task.We need to restrict the employee object and trip object which is shown in objects and attachments column of the standard descision task.
    Let me have any suggestion on this.
    Thanks in advance.
    regards,
    Sabari Prabhu.

    Hi,
    I took a look into this same issue some time ago, and at least I didn't find a way to restrict only certain attachments for displaying in UWL. If the attachments cannot be hidden, I have tried to avoid using the business objects as much as possible. For example the employee object is many times binded to the task only because you want to display certain attributes in the task description. Then I have just binded the needed attributes into separate container elements. Of course this will not solve all the cases.
    Then other useful options are that you change the default method, and this method is implemented in a way that it either does not display anything, or displays something (maybe just an error message etc.) that makes more sense than the default method that SAP delivers. Or then you can implement for example your own web dynpro application that will be launched when you click the attachment.
    Regards,
    Karri

  • Error:Work item 000000001099:Object FLOWITEM method EXECUTE cannot be execu

    Hello experts,
    I have created a Sales order workflow whr after creation sales order will go to 1 person inbox and he will check the SO thoroughly and thn i hv added a user decision step for APPROVED or REJECTED for same person.
    Now after creation of sales order it goin to the person inbox for checkin SO but when he is saving it thn decision screen with button APPROVED or REJCTED is not coming and m getting error :Work item 000000001099: Object FLOWITEM method EXECUTE cannot be executed. and error: Error when processing node '0000000024' (ParForEach index 000000)
    i checked the agent mapping for both step....and thr is no error in agent mappin...in both steps i have mapped same rule with responsibility IDs
    PLz suggest urgently wht can be cause of error.
    Regards
    Nitin

    Hi Nitin,
    I think this seems to be an agent assignment issue.
    To debug this issue go to the workflow log and check if the agents are correctly being picked by the rule or not. Simulate the rule and check for the agents being picked.
    In the workflow log, check the agent for the User Decision step. If there is no agent found then there might be some issue with the data passed to rule.
    Hope this helps!
    Regards,
    Saumya

Maybe you are looking for

  • How do I control a data log session with period and sample time?

    I need a data logging system where the operator can select 2 logging parameters: Log Period and Sample Time. I also need a START and STOP button to control the logging session. For example, set the log period for 1 hour and the sampling time for 1 se

  • Error while downloading data into excel file.

    Hi,     I have a requirement to download data available in xstring to excel file. I have a RFC which has export parameter 'file_data' of type xstring. When i call RFC from web dynpro abap application it gives data out pout in xstring format. I am ope

  • Use of 8cm dvd from handycam for editing

    Hi just got my first mac yesterday very pleased, I have a sony DCR-DVD105E handycam, this records straight to 8cm Dvd. Does my mac take this size dvd before I just pop it in and can't get it back out? if not can anyone help me as how to edit using my

  • Uploading ibooks... when to stop?!

    im uploading ibook to itunes and it seems there is no way of know its done.... after uploading the book here is what i got: the next button is grayed out... it seems like deliver button is the only viable option. but ive been clicking the deliver a f

  • Opening photos to view on tv

    I have scanned hundreds of photos and have put them on cd to view on the tv. I have adjusted some in photoshop and saved as jpgs but for some reason the ones that I have adjusted wont open on the tv.  need help desperately as I am wasting discs.