001 package com.croftsoft.core.util;
002
003 import com.croftsoft.core.lang.lifecycle.Resumable;
004
005 /*********************************************************************
006 * Used for timing events with millisecond precision.
007 *
008 * @version
009 * 2001-07-03
010 * @since
011 * 2001-07-03
012 * @author
013 * <a href="https://www.croftsoft.com/">David Wallace Croft</a>
014 *********************************************************************/
015
016 public final class Stopwatch
017 implements Resumable
018 //////////////////////////////////////////////////////////////////////
019 //////////////////////////////////////////////////////////////////////
020 {
021
022 private long elapsedTime;
023
024 private boolean isTicking;
025
026 private long startTime;
027
028 //////////////////////////////////////////////////////////////////////
029 //////////////////////////////////////////////////////////////////////
030
031 /*********************************************************************
032 * Returns the elapsed time in milliseconds.
033 *********************************************************************/
034 public synchronized long getElapsedTime ( )
035 //////////////////////////////////////////////////////////////////////
036 {
037 if ( isTicking )
038 {
039 return System.currentTimeMillis ( ) - startTime;
040 }
041 else
042 {
043 return elapsedTime;
044 }
045 }
046
047 //////////////////////////////////////////////////////////////////////
048 //////////////////////////////////////////////////////////////////////
049
050 public synchronized void reset ( )
051 //////////////////////////////////////////////////////////////////////
052 {
053 elapsedTime = 0;
054
055 isTicking = false;
056 }
057
058 public synchronized void start ( )
059 //////////////////////////////////////////////////////////////////////
060 {
061 if ( isTicking )
062 {
063 throw new IllegalStateException ( "already started" );
064 }
065
066 isTicking = true;
067
068 startTime = System.currentTimeMillis ( );
069 }
070
071 public synchronized void stop ( )
072 //////////////////////////////////////////////////////////////////////
073 {
074 if ( !isTicking )
075 {
076 throw new IllegalStateException ( "not started" );
077 }
078
079 elapsedTime = System.currentTimeMillis ( ) - startTime;
080
081 isTicking = false;
082 }
083
084 //////////////////////////////////////////////////////////////////////
085 //////////////////////////////////////////////////////////////////////
086 }