View Javadoc
1   /*
2    * Copyright (C) 2011 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.base;
16  
17  import com.google.common.annotations.Beta;
18  import com.google.common.annotations.GwtCompatible;
19  import com.google.errorprone.annotations.CanIgnoreReturnValue;
20  
21  /**
22   * A time source; returns a time value representing the number of nanoseconds elapsed since some
23   * fixed but arbitrary point in time. Note that most users should use {@link Stopwatch} instead of
24   * interacting with this class directly.
25   *
26   * <p><b>Warning:</b> this interface can only be used to measure elapsed time, not wall time.
27   *
28   * @author Kevin Bourrillion
29   * @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility">mostly
30   *     source-compatible</a> since 9.0)
31   */
32  @Beta
33  @GwtCompatible
34  public abstract class Ticker {
35    /**
36     * Constructor for use by subclasses.
37     */
38    protected Ticker() {}
39  
40    /**
41     * Returns the number of nanoseconds elapsed since this ticker's fixed point of reference.
42     */
43    @CanIgnoreReturnValue // TODO(kak): Consider removing this
44    public abstract long read();
45  
46    /**
47     * A ticker that reads the current time using {@link System#nanoTime}.
48     *
49     * @since 10.0
50     */
51    public static Ticker systemTicker() {
52      return SYSTEM_TICKER;
53    }
54  
55    private static final Ticker SYSTEM_TICKER =
56        new Ticker() {
57          @Override
58          public long read() {
59            return Platform.systemNanoTime();
60          }
61        };
62  }