This discussion is archived
1 2 Previous Next 17 Replies Latest reply: Mar 14, 2013 10:30 AM by rp0428 RSS

how to know when an object is deleted?

mrsAngelo Newbie
Currently Being Moderated
Hi,

In Java, instances of classes are eliminate by garbage collector and programmers have no chance to do it.

I need to do something, when the instance of a class ends its cycle-life .
How do I know when an object is going to be deleted, in order to make some thing bounded to this event?

thank you

Regards

Angelo
  • 1. Re: how to know when an object is deleted?
    baftos Expert
    Currently Being Moderated
    Your object's finalize() method will be called at some point between the moment the object is not referenced anymore and the end of the solar system. I am serious, there is no guarantee about when your object will be finalized at all.
    Therefore, I would suggest you don't count on it or tell us what is the action to be done when this happens. In Java there are other strategies that are used instead of rellying on finalize() usually.
  • 2. Re: how to know when an object is deleted?
    mrsAngelo Newbie
    Currently Being Moderated
    Hi batfos,

    thank you for answering me.

    I know very well that the method finalize is not affordable...

    --------
    My problem come for using a JS2E JavaBean that I made myself...
    This JavaBean raises events and, of curse, the users (the classes that use the JavaBean) have to be registered as listeners for it.

    When I run more than one class that use the javaBean; the JaveBean always (and only) talks with the first listener (class) that is been registered.

    It need to manage the remotion of the listeners.

    I have not much experience with this mechanism and, at the moment, I solved artlessly my problem using a method that remove all the listeners from the JavaBean when the listener (the class) classes stop to work.

    I should have to manage the removal of the listeners in a way more proper .. but I haven't experience with this kind of work...

    I need some help to do it well.

    Regards

    Angelo
  • 3. Re: how to know when an object is deleted?
    gimbal2 Guru
    Currently Being Moderated
    It need to manage the remotion of the listeners.
    The removing of them you mean?
  • 4. Re: how to know when an object is deleted?
    r035198x Pro
    Currently Being Moderated
    See if you can't use the Observer pattern: http://java.dzone.com/articles/design-patterns-uncovered
  • 5. Re: how to know when an object is deleted?
    mrsAngelo Newbie
    Currently Being Moderated
    yes I mean removing the listeners.

    If it is more than one class that use the JavaBean, then the JavaBean continues to answer to the events of the "object that was registered the first" (applies the calls to the instance of that class..), ...also if (when) this object stopped to run.

    I have to go more in deep of this mechanism...
    At the moment I know for sure that the JavaBean works properly, if I remove all the listener from it when the "his user object" stop to run.

    Thank you for the link, it seems to be a good way to follow

    Regards

    Angelo
  • 6. Re: how to know when an object is deleted?
    EJP Guru
    Currently Being Moderated
    the JaveBean always (and only) talks with the first listener (class) that is been registered
    So you have a bug in your JavaBean class.
    It need to manage the remotion of the listeners.
    No, it needs to call all the listeners that are still registered. None of the listeners will be GC'd if they are still registered. You have a bug in your code.\
    then the JavaBean continues to answer to the events of the "object that was registered the first" (applies the calls to the instance of that class..)
    Only if you have bugs in your code.
    ...also if (when) this object stopped to run.
    If there are reachable listeners, the object itself won't be GC'd at all.

    Is this a real question?
  • 7. Re: how to know when an object is deleted?
    r035198x Pro
    Currently Being Moderated
    EJP wrote:
    If there are reachable listeners, the object won't be GC'd at all.

    Is this a real question?
    It's difficult to read but it sounds to me like they are failing to remove the individual listeners and have only been able to remove all of them.
  • 8. Re: how to know when an object is deleted?
    gimbal2 Guru
    Currently Being Moderated
    EJP wrote:
    No, it needs to call all the listeners that are still registered. None of the listeners will be GC'd if they are still registered. You have a bug in your code.\
    Unless they are WeakReference'd. But I give that a very small chance in this case, I just want to be a smarty pants.
  • 9. Re: how to know when an object is deleted?
    mrsAngelo Newbie
    Currently Being Moderated
    A moment...,

    I have not a big experience with JavaBeans and with the Events..
    That that I made, is my first JavaBeans and I didn't removed no one of individuals listeners inside it... :-(.
    Perhaps this is the bug that EJP talk about.

    ----
    In my state of insecurity, biting on a situation that I don't know very well, I was only surprised that an object that I think to be dead can still work to call methods of objects (sources of events).

    Also...:
    I paid attention to indicate exactly (in the class that describe the events) the source that raise the events.
    But, in the tests that I made, I didn't have success to manage the bug using this information.
    Using the information of the source, in order to select the sources that I was interested to, the source that I expected never came.
    ----

    At the last ...(practically).... I can deduce that removing (time to time) the individual events, I can hope to solve my problem.
    This is what you think about ?

    Regards

    Angelo
  • 10. Re: how to know when an object is deleted?
    baftos Expert
    Currently Being Moderated
    In what way is your JavaBean special? Why all the many examples all over the web don't apply to you?
    Maybe you can post some code, especially the add/remove listeners methods and their use?
  • 11. Re: how to know when an object is deleted?
    mrsAngelo Newbie
    Currently Being Moderated
    hi baftos,

    the JavaBean is named DBNavigator.
    It is connected with a table of a database to show his data.

    -----
    It can be used together another JavaBean named DBOperationBean that allow
    to manipulate the data of the same table.

    These JavaBeans are in my project that I published on Surgeforge at the
    link : https://sourceforge.net/projects/swing-database/ with the
    name "Swing toolkit to access a table of a database".

    This project is not finished because I am still working on it
    and, also I am already using it, it can contain bugs ...

    The source of the JavaBeans can be downloaded.

    Thank you for your time

    Regards

    Angelo
  • 12. Re: how to know when an object is deleted?
    gimbal2 Guru
    Currently Being Moderated
    You've hit a dead end - you are now expecting people to download the source and go hunt for the bugs in it for you. That isn't going to happen. Do the work yourself and post relevant code here that you need help with.
  • 13. Re: how to know when an object is deleted?
    EJP Guru
    Currently Being Moderated
    This is what you think about ?
    I don't know what you're talking about. Neither does anybody else. Deleted objects don't run any code. What is the actual problem you are trying to solve? and what is the code concerned?
  • 14. Re: how to know when an object is deleted?
    mrsAngelo Newbie
    Currently Being Moderated
    Thank you for your help ...

    Here some code (I hope that I didn't forget something important):

    1. A class inside the JaveaBeans to manage events:
    /**
         * NavBean_EventsBroadcaster is a singleton class used in the JavaBean to manage (fire)
         * the events; and also to manage (add/remove) the listeners.
         * ---------------------------
         * Events are raised when users push buttons with the purpose to change the display of
         * records (of the table) on the screen.
         */
        public class NavBean_EventsBroadcaster implements Serializable {
    
            private transient Vector listeners;
            private static NavBean_EventsBroadcaster eventsBroadcaster_ForNavBeans = null;
    
             /**
             Method to get the instance of the singleton class
             */
               static public NavBean_EventsBroadcaster getSingletonInstance() {
                    if (eventsBroadcaster_ForNavBeans == null) {
                        eventsBroadcaster_ForNavBeans = new NavBean_EventsBroadcaster();
                    }
                    return eventsBroadcaster_ForNavBeans;
                } // getSingletonInstance
    
    
    
           /**
            * fireTheEvent_X_navBean(): method that raise events
            */
            public void fireTheEvent_X_navBean(
                    Object source,
                    NavigatorBean_eventsList_ENUM nbEvtENUM,
                    ResultSet rst,
                    int keyReg) {
    
                if (listeners != null && !listeners.isEmpty()) {
                    // object is going to be created (it contains the infos about the event)
                    NavBeanDB_EventDescriptor event_descr =
                            new NavBeanDB_EventDescriptor(
                            source, // dBbeanNavigator
                            nbEvtENUM,
                            rst,
                            keyReg);
    
                    // copy of the lisener to use it for add or remove
                    Vector targets;
                    synchronized (this) {
                        targets = (Vector) listeners.clone();
                    }
    
                    // proper event (select first, next, prev, last reg) is raised
                    Enumeration enumerat = targets.elements();
                    while (enumerat.hasMoreElements()) {
                        NavBeanDBListener_INTERFACE l =
                               (NavBeanDBListener_INTERFACE) enumerat.nextElement();
                        l.firedNavigationBeanEvents(event_descr);
                        System.out.println("Method fireTheEvent ----- key = " + priKeyOnTheScreen);
                    }
                }  // if
        } // fireTheEvent()
    
    
            /**
             * Adds a listener to the listener list.
             *
             * @param l The listener to add.
             */
            synchronized public void addNavBeanAddListener(NavBeanDBListener_INTERFACE l) {
                if (listeners == null) {
                    listeners = new Vector();
                }
                listeners.addElement(l);
                System.out.println("E' stato registrato un nuovo ascoltatatore per navigationBar");
            } // addNavBeanAddListener()
    
    
    
        /**
         * Removes a listener from the listener list.
         *
         * @param l The listener to remove.
         */
        synchronized public void removeNavBeanRemoveListener(NavBeanDBListener_INTERFACE l) {
            if (listeners.contains(l)) {
                listeners.remove(l);
            }
        }  // removeNavBeanRemoveListener()
    
        } // class NavBean_EventsBroadcaster
    2. The used interface
         /**
          * This is the interface that specifies the contract between a NavBeans 
          * source and listener classes.
          * @author Owner
          */
         
         public interface NavBeanDBListener_INTERFACE extends EventListener {
             public void firedNavigationBeanEvents(NavBeanDB_EventDescriptor evt);
         
         } // interface NavDB_BeansListener_INTERFACE
    3. the class adapter
        public abstract class DbNavigatorBean_Adapter implements NavBeanDBListener_INTERFACE {
         
             NavigatorBean_eventsList_ENUM navigatorBean_eventsList_ENUM;
         
             public DbNavigatorBean_Adapter() { // costruttore
             } // costruttore
         
             /**
              * This class have to be implemented from listeners to get events.
              * 
              * @param evt
              */
             // NavigatorBean_eventsList_ENUM {user_chang, sequential_first, sequential_prev, sequential_next, sequential_last}
             public void firedNavigationBeanEvents(NavBeanDB_EventDescriptor evt) {
                 navigatorBean_eventsList_ENUM = evt.getEventType();
         
                 switch (navigatorBean_eventsList_ENUM) {
                     case user_chang:
                         toDoWhen_user_changeRegistration(evt);
                         break;
                     case sequential_first:
                         toDoWhen_setted_firstRegistration(evt);
                         break;
                     case sequential_prev:
                         toDoWhen_setted_prevRegistration(evt);
                         break;
                     case sequential_next:
                         toDoWhen_setted_nextRegistration(evt);
                         break;
                     case sequential_last:
                         toDoWhen_setted_lastRegistration(evt);
                         break;
                 } // witch case
         
             } // firedNavigationBeanEvents()
         
             abstract public void toDoWhen_user_changeRegistration(NavBeanDB_EventDescriptor evt); // { }
         
             abstract public void toDoWhen_setted_firstRegistration(NavBeanDB_EventDescriptor evt); // { }
         
             abstract public void toDoWhen_setted_nextRegistration(NavBeanDB_EventDescriptor evt); // { }
         
             abstract public void toDoWhen_setted_prevRegistration(NavBeanDB_EventDescriptor evt); // { }
         
             abstract public void toDoWhen_setted_lastRegistration(NavBeanDB_EventDescriptor evt); // { }
         } // class class DbNavigatorBean_Adapter_base
    4. the class used to describe the event
       /**
       Class used to dercribe the event that happened.
       */
       public class NavBeanDB_EventDescriptor extends EventObject {
       
           private NavigatorBean_eventsList_ENUM navigationBean_events_ENUM;
           private int primaryKeyOfRegOnTheScreen;
           private ResultSet resultSet;
           private int totOfRegsRegistredOnTheTable;
       
           /**
            * Costructor: is used to describe the events
            * -----------------
            * @param source
            * @param nbEvtENUM
            * @param rst
            * @param keyReg
            */
           public NavBeanDB_EventDescriptor( // costruttore
                   Object source,
                   NavigatorBean_eventsList_ENUM nbEvtENUM,
                   ResultSet rst,
                   int keyReg) { 
               super(source);
               this.navigationBean_events_ENUM = nbEvtENUM;
               this.resultSet = rst;
               this.primaryKeyOfRegOnTheScreen = keyReg;
               extractTotRegsInTheTable(rst);
       //        this.totOfRegsRegistredOnTheTable = rgsRegNmbr;
               System.out.println("Viene creata una istanza di event descriptor");
           }// costruttore
       
           /**
            * which possibe action caused the event, 
            * was pushed the button (first, prev, next, last, user select...)
            * @return
            */
           public NavigatorBean_eventsList_ENUM getEventType() {
               return navigationBean_events_ENUM;
           } // getEventType
       
           /**
            * primmary key of registration on the screen
            * 
            * @return
            */
           public int getPrimaryKeyOfTheRegOnTheScreen() {
               return primaryKeyOfRegOnTheScreen;
           } // getKeyRegOnTheScreen
       
           /**
           * resultSet showed on the screen
           */
           public ResultSet getTheFullRegistrationOnTheScreen() {
               return resultSet;
           } // getTheFullRegistrationOnTheScreen
       
           /**
           Number of registrations actually on the table.
           */
           public int getTotRegsRegistredOnTheTable() {
               return this.totOfRegsRegistredOnTheTable;
           } // getRegsRegistredNmbr
       
           /**
            private classe that get data
           */
           private void extractTotRegsInTheTable(ResultSet rst) {
               ResultSet localRst =rst;
               try {
                   int curRow = localRst.getRow();
                   localRst.last();
                   this.totOfRegsRegistredOnTheTable = localRst.getRow();
                   localRst.absolute(curRow);
               } catch (SQLException ex) {
                   Logger.getLogger(NavBeanDB_EventDescriptor.class.getName()).log(Level.SEVERE, null, ex);
               }
               
           }
       } // class NavBeansEvent
    5. a possible use of the JavaBeans
       
       public class TableClients extends JFrame 
           implements LinkTablesToDlgThatRandomizeSelections_INTERFACE {
       private NavigationBean navigationBean;
       
       
       public TableClients() {   // constructor
            navigationBean = new NavigationBean();
            navigationBean.initializeDBbeanNavigator(...);
            
            
            this.add(navigationBean);
            navigationBean.addActionNavigatorListener(new DbNavigatorBean_Adapter() {
                        @Override
                        public void toDoWhen_user_changeRegistration(NavBeanDB_EventDescriptor nbdbed) {
                            // do something
                        }
            
                        @Override
                        public void toDoWhen_setted_firstRegistration(NavBeanDB_EventDescriptor nbdbed) {
                                // do something
                        }
            
                        @Override
                        public void toDoWhen_setted_nextRegistration(NavBeanDB_EventDescriptor nbdbed) {
                                // do something
                        }
            
                        @Override
                        public void toDoWhen_setted_prevRegistration(NavBeanDB_EventDescriptor nbdbed) {
                                // do something
                        }
            
                        @Override
                        public void toDoWhen_setted_lastRegistration(NavBeanDB_EventDescriptor nbdbed) {
                                // do something
                        }
                    });
    
            
    } // constructor
    
    
    } // class TableClients
    this code works well...

    But if I implement the javaBeans on more than one Dialogs (windows) and the user uses
    this dialogs sequentially, then the JavaBean responds to the events always as the caller is the
    first dialog that run...

    If I delete all listener (on the dialog) when the dialog is close then I have not problems

    still thank you

    Regards

    Angelo
1 2 Previous Next

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points