001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.util;
018
019/**
020 * A very simple stop watch.
021 * <p/>
022 * This implementation is not thread safe and can only time one task at any given time.
023 */
024public final class StopWatch {
025
026    private long start;
027    private long stop;
028
029    /**
030     * Starts the stop watch
031     */
032    public StopWatch() {
033        this(true);
034    }
035
036    /**
037     * Creates the stop watch
038     *
039     * @param started whether it should start immediately
040     */
041    public StopWatch(boolean started) {
042        if (started) {
043            restart();
044        }
045    }
046
047    /**
048     * Starts or restarts the stop watch
049     */
050    public void restart() {
051        start = System.currentTimeMillis();
052        stop = 0;
053    }
054
055    /**
056     * Stops the stop watch
057     *
058     * @return the time taken in milliseconds.
059     */
060    public long stop() {
061        stop = System.currentTimeMillis();
062        return taken();
063    }
064
065    /**
066     * Returns the time taken in milliseconds.
067     *
068     * @return time in milliseconds
069     */
070    public long taken() {
071        if (start > 0 && stop > 0) {
072            return stop - start;
073        } else if (start > 0) {
074            return System.currentTimeMillis() - start;
075        } else {
076            return 0;
077        }
078    }
079}