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?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
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.