title: thread-safe stopwatch API
body: <p>I am wondering how to write a thread-safe stopwatch. Below is a simple stopwatch implementation, and it provide basic operations of a stopwatch, but it is not thread-safe.</p>
  
  <p>Now, all that I can think about is to add synchronize to each methods (start(), lap(), stop(), reset()). Is there exist some other way to achieve thread-safety on the stopwatch? </p>
  
  <pre><code>import java.util.List;
  import java.util.concurrent.CopyOnWriteArrayList;
  
  public class Stopwatch {
      private long startTime;
      private long endTime;
      private boolean isRunning;
  
      // lapTimes is able to record all the lap time.
      private CopyOnWriteArrayList&lt;Long&gt; lapTimes;
  
      Stopwatch() {
          isRunning = false;
          lapTimes = new CopyOnWriteArrayList&lt;Long&gt;();
      }
  
      public void start() {
          if (!isRunning) {
              isRunning = true;
              startTime = System.currentTimeMillis();
          } else {
              throw new IllegalStateException("cannot start when running!");
          }
      }
  
      public void lap() {
          if (isRunning) {
              endTime = System.currentTimeMillis();
              lapTimes.add(endTime - startTime);
              startTime = endTime;
          } else {
              throw new IllegalStateException("cannot lap when not running!!");
          }
      }
  
      public void stop() {
          if (isRunning) {
              endTime = System.currentTimeMillis();
              lapTimes.add(endTime - startTime);
              isRunning = false;
          } else {
              throw new IllegalStateException("cannot stop when not running!");
          }
      }
  
      public void reset() {
          isRunning = false;
          lapTimes.clear();
      }
  
      public List&lt;Long&gt; getLapTime() {
          return lapTimes;
      }
  </code></pre>
  
  <p>}</p>
  
  <p>What I want to do is to share one stopwatch object by multiple threads.</p>
  
  <p>Suppose we have two threads: thread A and thread B. Thread A start the stopwatch, and several seconds late, it called stop. While it just finished if statement(the first line in stop method), thread B was invoked, and it also called stop method. Later, thread A continued to execute stop method without any exceptions.</p>
  
  <p>This is not what I want, since a thread-safe stopwatch could not be stopped twice, and I just want to know how to get rid of it.</p>