4

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.

Dolf
  • 134
  • 9

3 Answers3

4

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);
        }

    }

}
wthamira
  • 2,032
  • 2
  • 21
  • 40
  • This might be useful for my other uses, but sadly it can only show the time when being destroyed. – Dolf Jan 21 '17 at 06:41
  • did you run my code? it gives starting time and destroy time. Then you can write algorithm for existed time. Can you explain more about your problem. – wthamira Jan 21 '17 at 06:47
  • My problem is that I am trying to find a way to get the existing time of an object, which is not overrided, whenever I want, instead of only being able to get the time only when the finalize() is called. – Dolf Jan 21 '17 at 06:53
  • It is not general purpose of object. In java no implementation for that. Read documentation of Object.class after you can write customised object for that and extend it to your object. I can write it and send you latter. – wthamira Jan 21 '17 at 07:06
  • 1
    FYI, the old [`Calendar`](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html) and [`Date`](http://docs.oracle.com/javase/8/docs/api/java/util/Date.html) classes are now [legacy](https://en.wikipedia.org/wiki/Legacy_system). Supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. – Basil Bourque Jan 21 '17 at 23:48
  • Thank you. @basil_bourque I try to explain his perpose only. we can change that to java.time – wthamira Jan 21 '17 at 23:55
3

There's no automatic way to do this, no getTime(obj) method present. The only way to do this is to write code yourself to manually retrieve the system time, often done via System.currentTimeMillis() when and where needed, and then subtracting the values thus obtained to get a duration or time-difference.

Now you can create a class that you yourself wire to have this functionality, that obtains its own creation time and stores it in a field, and than has its own methods that return duration of existence, and in fact this would be easy to do, and its implementation will be left as an exercise for the student.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

tl;dr

Duration.between( objectBorn , Instant.now() )

java.time

The answer by lakmal looks to be correct except that it uses the troublesome old date-time classes now legacy, supplanted by the java.time classes.

As the other Answer explains, Java objects do not track their time in existence by default. You must add your own code to track their birth and age.

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now();  // Current moment in UTC.

In Java 8, the current moment is captured with a precision of milliseconds (or coarser granularity, depending on your computer hardware clock). In Java 9 and later, a fresh implementation of Clock increases the potential precision to nanoseconds, depending on the capability of your computer hardware clock. To be clear, in both Java 8 and Java 9 you can represent a moment with up to nanoseconds resolution; only capturing the current moment is limited in Java 8.

Duration

The Duration class represents a span of time.

Here is a complete example.

package javatimestuff;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Basil Bourque
 */
public class Life {

    private Instant objectBorn = null;

    // Constructor
    public Life () {
        this.objectBorn = Instant.now ();  // Capture the moment at birth of this object.
    }

    public Duration objectAgeAsDuration () {
        Duration d = Duration.between ( objectBorn , Instant.now () );
        return d;
    }

    public long objectAgeAsNanos () {
        Duration d = this.objectAgeAsDuration ();
        return d.toNanos ();
    }

}

Exercise that class.

    public static void main ( String[] args ) {
        System.out.println ( "Please wait a few seconds as we birth a new `Life` object. " );

        Life l = new Life ();
        try {
            Thread.sleep ( TimeUnit.SECONDS.toMillis ( 3 ) );
        } catch ( InterruptedException ex ) {
            // Interruption may be this thread being woken.
            // …
        }

        System.out.println ( "The Life object’s age as Duration: " + l.objectAgeAsDuration () );
        System.out.println ( "The Life object’s age as nanoseconds: " + l.objectAgeAsNanos () );
    }

Please wait a few seconds as we birth a new Life object.

The Life object’s age as Duration: PT3.002S

The Life object’s age as nanoseconds: 3010000000

finalize is irrelevant and not dependable

Your comments talk about wanting to get the time when an object’s finalize method runs. You should know two important things in that regard:

  • finalize happens after an object becomes a candidate for garbage collection, any time after. It may happen quickly or it may be quite a while later. The scheduling is up to the implementation of Java, not specified by the Java spec.
  • finalize may not run at all. For example, a JVM may exit while choosing to immediately clear all objects including the garbage-collection candidates without executing the finalize methods at all.

Generally speaking, the finalize method is of little practical use. Common practice is define and call your own method (teardown, shutdown, whatever name you want) to immediately release any resources when finished using an object.

The Object::finalize() method has been officially deprecated in Java 9 and later as documented here and discussed here. To quote the doc:

Deprecated. The finalization mechanism is inherently problematic. Finalization can lead to performance issues, deadlocks, and hangs. Errors in finalizers can lead to resource leaks; there is no way to cancel finalization if it is no longer necessary; and no ordering is specified among calls to finalize methods of different objects. Furthermore, there are no guarantees regarding the timing of finalization. The finalize method might be called on a finalizable object only after an indefinite delay, if at all. Classes whose instances hold non-heap resources should provide a method to enable explicit release of those resources, and they should also implement AutoCloseable if appropriate. The Cleaner and PhantomReference provide more flexible and efficient ways to release resources when an object becomes unreachable.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154