1 /* 2 * Copyright (C) 2008 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.testing; 18 19 import static com.google.common.base.Preconditions.checkArgument; 20 21 import com.google.common.annotations.Beta; 22 import com.google.common.annotations.GwtCompatible; 23 import com.google.common.base.Ticker; 24 25 import java.util.concurrent.TimeUnit; 26 import java.util.concurrent.atomic.AtomicLong; 27 28 /** 29 * A Ticker whose value can be advanced programmatically in test. 30 * <p> 31 * The ticker can be configured so that the time is incremented whenever {@link #read} is called: 32 * see {@link #setAutoIncrementStep}. 33 * <p> 34 * This class is thread-safe. 35 * 36 * @author Jige Yu 37 * @since 10.0 38 */ 39 @Beta 40 @GwtCompatible 41 public class FakeTicker extends Ticker { 42 43 private final AtomicLong nanos = new AtomicLong(); 44 private volatile long autoIncrementStepNanos; 45 46 /** Advances the ticker value by {@code time} in {@code timeUnit}. */ advance(long time, TimeUnit timeUnit)47 public FakeTicker advance(long time, TimeUnit timeUnit) { 48 return advance(timeUnit.toNanos(time)); 49 } 50 51 /** Advances the ticker value by {@code nanoseconds}. */ advance(long nanoseconds)52 public FakeTicker advance(long nanoseconds) { 53 nanos.addAndGet(nanoseconds); 54 return this; 55 } 56 57 /** 58 * Sets the increment applied to the ticker whenever it is queried. 59 * 60 * <p>The default behavior is to auto increment by zero. i.e: The ticker is left unchanged when 61 * queried. 62 */ setAutoIncrementStep(long autoIncrementStep, TimeUnit timeUnit)63 public FakeTicker setAutoIncrementStep(long autoIncrementStep, TimeUnit timeUnit) { 64 checkArgument(autoIncrementStep >= 0, "May not auto-increment by a negative amount"); 65 this.autoIncrementStepNanos = timeUnit.toNanos(autoIncrementStep); 66 return this; 67 } 68 read()69 @Override public long read() { 70 return nanos.getAndAdd(autoIncrementStepNanos); 71 } 72 } 73