Search code examples
javastopwatch

Java StopWatch Suspend and Resume timer not working


The purpose of below code is to test the StopWatch for reset, start, suspend and resume. It should be possible to suspend a stopwatch at a given point in time and resume it later. In this case the elapse time is the cumulative total of all suspend and resume events when the timer is eventually stopped. The code works fine if i remove timer.suspend() and timer.resume(). When i run the code, thread goes to sleep for 2.3 seconds and give elapsed time 2300 in output. However, with suspend and resume method, it sleeps for 2.3 seconds but give output of 0.

Can you please suggest/advice what is wrong in the code?

Thank you.

 interface StopWatch {

public void reset();
public void start();
public void stop();
public void suspend();
public void resume();
public long getElapsedTime();
public int getState();
public static final int RESET = 0, RUNNING =1, STOPPED =2, SUSPENDED = 3, RESUME = 0;}

Timer Class

class Timer implements StopWatch{
private long startTime;
private long elaspedTime;
private int state;
public Timer(){reset();}

public void reset(){
    state = RESET;
    elaspedTime = 0;
}
public void start(){
    if(state==RESET){
        startTime = System.currentTimeMillis();
        state = RUNNING;
        }
}     

public void stop(){

    if(state == RUNNING){
        elaspedTime = System.currentTimeMillis() - startTime;
        state = STOPPED;
    }
}
public void suspend() {
    if(state == RUNNING){
        elaspedTime = System.currentTimeMillis() - startTime;
        state = SUSPENDED;
    }
}
public void resume(){

    if(state == RUNNING){
        elaspedTime = System.currentTimeMillis() - startTime;
        state = RESUME;
    }
}

public long getElapsedTime() {
    if(state == RUNNING){
        long elasped = System.currentTimeMillis() - startTime;
        return elasped;
    }
    else if (state == STOPPED)
        return elaspedTime;

    else if (state == RESUME)
        return elaspedTime;
    return 0;
}
public int getState(){
    return state;
}}

StopWatch Test

 public class StopWatchTest {
        public static  void main (String[] args){
        Timer timer = new Timer();
        timer.start();
        try{
            Thread.sleep(2300);
            timer.suspend();
            timer.resume();
        }catch (InterruptedException e){}
        timer.stop();
        long duration = timer.getElapsedTime();
        System.out.println(duration);
    }}

Solution

  • if(state == RUNNING){
        elaspedTime = System.currentTimeMillis() - startTime;
        state = RESUME;
    }
    

    In the resume method you are checking if the stopwatch is running, how can you resume an already running stopwatch?

    Change RUNNING to SUSPENDED in your resume method.