views:

486

answers:

4

Is there a way to find out the time since the JVM started?

Of course, other than starting a timer somewhere near the beginning of main, because in my scenario I am writing library code and the requirement that something be called immediately after startup is a too burdensome.

A: 

What exactly do you need this for. If it is for logging purposes then most logging frameworks allow you to get this value directly as part of the logging context.

Otherwise store the value of System.currentTimeMillis() in a long in a static field in the first class in your API that gets pulled in. That is the earliest you may execute code without changing the calling program.

Thorbjørn Ravn Andersen
+10  A: 

Use this snippet:

long jvmUpTime = ManagementFactory.getRuntimeMXBean().getUptime();

or:

long jvmStartTime = ManagementFactory.getRuntimeMXBean().getStartTime();

This is the correct way of retrieving JVM up-time.

For more info see http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/RuntimeMXBean.html

Yuval A
+6  A: 

You can get the start time of the JVM in the following code:

import java.lang.management.ManagementFactory;
  import java.lang.management.RuntimeMXBean;
  ...
  RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
  long uptimeInMillis = runtimeMXBean.getUptime();

See more are http://java.sun.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html

David Rabinowitz
+1  A: 

Starting from Java 5, you can use JMX to find this out. Check "Using the platform MBeanserver" to find out more details. The bean you're looking for is the bean called "java.lang:type=Runtime". The attribute StartTime gives you the time the JVM was started and the Uptime attribute tells you the uptime of the JVM.

You can get a reference to the Runtime bean by executing this code: ManagementFactory.getRuntimeMXBean();

Gerco Dries