Class ThreadCpuTimer


  • @NotThreadSafe
    public class ThreadCpuTimer
    extends Object
    Allows tracking information about the current thread using the JVM's built-in management bean ThreadMXBean.

    Calling code should create an instance of this class when starting the operation, and then can get the getElapsedCpuMs() at any time thereafter.

    This class is irrevocably not thread safe. Never allow instances of this class to be exposed to more than one thread. Acquiring an external lock will not be sufficient. This class can be considered "lock-hostile" due to its caching of timing information for a specific thread.

    • Constructor Detail

      • ThreadCpuTimer

        public ThreadCpuTimer()
        Create an instance to track the current thread's usage of CPU. Usage information can later be retrieved by calling getElapsedCpuMs(). Timing starts immediately upon construction.
    • Method Detail

      • isSupported

        public static boolean isSupported()
      • getElapsedCpuNs

        public long getElapsedCpuNs()
        Return CPU time consumed by this thread since the construction of this timer object.
        Returns:
        current value, or UNSUPPORTED if not supported.
      • getElapsedCpuMs

        public Optional<Long> getElapsedCpuMs()
        Get the CPU usage information for the current thread since it created this ThreadCpuTimer. The result is undefined if called by any other thread.
        Returns:
        the thread's cpu since the creation of this ThreadCpuTimer instance. If the VM's cpu tracking is disabled, returned value will be UNSUPPORTED.