Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Getting the existing time of an object

Tags:

java

oop

Let's say I created an object, like this

Object obj = new Object();

Now I want to get how long has the object existed, like

System.out.println("Creating object");
Object obj = new Object();
//Print 0
System.out.println("The object has existed for (ms): " + getTime(obj));
Thread.sleep(1000);
//Print 1000
System.out.println("The object has existed for (ms): " + getTime(obj));

How can I do so? Any help is appreciated.

like image 968
Dolf Avatar asked Jan 04 '23 16:01

Dolf


1 Answers

Try this code. finalize() method run in destroy time of object.if the the object goes to garbage collector that finalize method run. in my code System.gc() use for call garbase collector. This code is very long. its only for understanding purpose. You can customize this code.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Thamira
 */
public class Demostra {

    public static void main(String[] args) {

        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        System.out.println("Creating object :" + sdf.format(cal.getTime()));
        Object obj = new Object() {

            @Override
            protected void finalize() throws Throwable {
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                System.out.println("The object has removed for : " + sdf.format(cal.getTime()));

                super.finalize(); //To change body of generated methods, choose Tools | Templates.
            }

        };

        cal = Calendar.getInstance();
        sdf = new SimpleDateFormat("HH:mm:ss");

        System.out.println("The object has existed for : " + sdf.format(cal.getTime()));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Demostra.class.getName()).log(Level.SEVERE, null, ex);
        }

        cal = Calendar.getInstance();
        sdf = new SimpleDateFormat("HH:mm:ss");

        System.out.println("The object has existed for  : " + sdf.format(cal.getTime()));

        obj = null;

        System.gc();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Demostra.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}
like image 122
wthamira Avatar answered Jan 07 '23 07:01

wthamira