View Javadoc
1   /*
2    * Copyright (C) 2016, Google Inc. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.util.time;
12  
13  import static java.util.concurrent.TimeUnit.MICROSECONDS;
14  import static java.util.concurrent.TimeUnit.MILLISECONDS;
15  
16  import java.time.Duration;
17  import java.util.concurrent.TimeUnit;
18  import java.util.concurrent.atomic.AtomicLong;
19  
20  /**
21   * A {@link org.eclipse.jgit.util.time.MonotonicClock} based on
22   * {@code System.currentTimeMillis}.
23   *
24   * @since 4.6
25   */
26  public class MonotonicSystemClock implements MonotonicClock {
27  	private static final AtomicLong before = new AtomicLong();
28  
29  	private static long nowMicros() {
30  		long now = MILLISECONDS.toMicros(System.currentTimeMillis());
31  		for (;;) {
32  			long o = before.get();
33  			long n = Math.max(o + 1, now);
34  			if (before.compareAndSet(o, n)) {
35  				return n;
36  			}
37  		}
38  	}
39  
40  	/** {@inheritDoc} */
41  	@Override
42  	public ProposedTimestamp propose() {
43  		final long u = nowMicros();
44  		return new ProposedTimestamp() {
45  			@Override
46  			public long read(TimeUnit unit) {
47  				return unit.convert(u, MICROSECONDS);
48  			}
49  
50  			@Override
51  			public void blockUntil(Duration maxWait) {
52  				// Assume system clock never goes backwards.
53  			}
54  		};
55  	}
56  }