summaryrefslogtreecommitdiffstats
path: root/timer/com/vladium/utils/timing/JavaSystemTimer.java
blob: e3f3b489f390fac8a31489e12244d77ea09fd63a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

package com.vladium.utils.timing;

// ----------------------------------------------------------------------------
/**
 * A package-private implementation of {@link ITimer} based around Java system
 * timer [<code>System.currentTimeMillis()</code> method]. It is used when
 * <code>HRTimer</code> implementation is unavailable.<P> 
 * 
 * {@link TimerFactory} acts as the Factory for this class.<P>
 * 
 * MT-safety: an instance of this class is safe to be used within the same
 * thread only.
 * 
 * @author (C) <a href="mailto:vroubtsov@illinoisalumni.org">Vlad Roubtsov</a>, 2002
 */
final class JavaSystemTimer implements ITimer, ITimerConstants 
{
    // public: ................................................................
    
    public void start ()
    {
        if (DO_STATE_CHECKS)
        {
            if (m_state != STATE_READY)
                throw new IllegalStateException (this + ": start() must be called from READY state, current state is " + STATE_NAMES [m_state]);
        }
        
        if (DO_STATE_CHECKS) m_state = STATE_STARTED;
        m_data = System.currentTimeMillis ();
    }
    
    public void stop ()
    {
        // latch stop time in a local var before doing anything else:
        final long data = System.currentTimeMillis ();
        
        if (DO_STATE_CHECKS)
        {
            if (m_state != STATE_STARTED)
                throw new IllegalStateException (this + ": stop() must be called from STARTED state, current state is " + STATE_NAMES [m_state]);
        }
        
        m_data = data - m_data;
        if (DO_STATE_CHECKS) m_state = STATE_STOPPED;
    }
    
    public double getDuration ()
    {
        if (DO_STATE_CHECKS)
        {
            if (m_state != STATE_STOPPED)
                throw new IllegalStateException (this + ": getDuration() must be called from STOPPED state, current state is " + STATE_NAMES [m_state]);
        }
        
        return m_data;
    }
    
    public void reset ()
    {
        if (DO_STATE_CHECKS) m_state = STATE_READY;
    }
    
    // protected: .............................................................

    // package: ...............................................................
        
    // private: ...............................................................
    
    private int m_state; // used to keep track of timer state
    private long m_data; // timing data

} // end of class
// ----------------------------------------------------------------------------