• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 package java.time;
26 
27 import java.time.Clock.SourceClock;
28 import java.time.Clock.SystemInstantSource;
29 import java.util.Objects;
30 
31 /**
32  * Provides access to the current instant.
33  * <p>
34  * Instances of this interface are used to access a pluggable representation of the current instant.
35  * For example, {@code InstantSource} can be used instead of {@link System#currentTimeMillis()}.
36  * <p>
37  * The primary purpose of this abstraction is to allow alternate instant sources to be
38  * plugged in as and when required. Applications use an object to obtain the
39  * current time rather than a static method. This can simplify testing.
40  * <p>
41  * As such, this interface does not guarantee the result actually represents the current instant
42  * on the time-line. Instead, it allows the application to provide a controlled view as to what
43  * the current instant is.
44  * <p>
45  * Best practice for applications is to pass an {@code InstantSource} into any method
46  * that requires the current instant. A dependency injection framework is one
47  * way to achieve this:
48  * <pre>
49  *  public class MyBean {
50  *    private InstantSource source;  // dependency inject
51  *    ...
52  *    public void process(Instant endInstant) {
53  *      if (source.instant().isAfter(endInstant) {
54  *        ...
55  *      }
56  *    }
57  *  }
58  * </pre>
59  * This approach allows an alternative source, such as {@link #fixed(Instant) fixed}
60  * or {@link #offset(InstantSource, Duration) offset} to be used during testing.
61  * <p>
62  * The {@code system} factory method provides a source based on the best available
63  * system clock. This may use {@link System#currentTimeMillis()}, or a higher
64  * resolution clock if one is available.
65  *
66  * @implSpec
67  * This interface must be implemented with care to ensure other classes operate correctly.
68  * All implementations must be thread-safe - a single instance must be capable of be invoked
69  * from multiple threads without negative consequences such as race conditions.
70  * <p>
71  * The principal methods are defined to allow the throwing of an exception.
72  * In normal use, no exceptions will be thrown, however one possible implementation would be to
73  * obtain the time from a central time server across the network. Obviously, in this case the
74  * lookup could fail, and so the method is permitted to throw an exception.
75  * <p>
76  * The returned instants from {@code InstantSource} work on a time-scale that ignores leap seconds,
77  * as described in {@link Instant}. If the implementation wraps a source that provides leap
78  * second information, then a mechanism should be used to "smooth" the leap second.
79  * The Java Time-Scale mandates the use of UTC-SLS, however implementations may choose
80  * how accurate they are with the time-scale so long as they document how they work.
81  * Implementations are therefore not required to actually perform the UTC-SLS slew or to
82  * otherwise be aware of leap seconds.
83  * <p>
84  * Implementations should implement {@code Serializable} wherever possible and must
85  * document whether or not they do support serialization.
86  *
87  * @implNote
88  * The implementation provided here is based on the same underlying system clock
89  * as {@link System#currentTimeMillis()}, but may have a precision finer than
90  * milliseconds if available.
91  * However, little to no guarantee is provided about the accuracy of the
92  * underlying system clock. Applications requiring a more accurate system clock must
93  * implement this abstract class themselves using a different external system clock,
94  * such as an NTP server.
95  *
96  * @since 17
97  */
98 public interface InstantSource {
99 
100     /**
101      * Obtains a source that returns the current instant using the best available
102      * system clock.
103      * <p>
104      * This source is based on the best available system clock. This may use
105      * {@link System#currentTimeMillis()}, or a higher resolution system clock if
106      * one is available.
107      * <p>
108      * The returned implementation is immutable, thread-safe and
109      * {@code Serializable}.
110      *
111      * @return a source that uses the best available system clock, not null
112      */
system()113     static InstantSource system() {
114         return SystemInstantSource.INSTANCE;
115     }
116 
117     //-------------------------------------------------------------------------
118     /**
119      * Obtains a source that returns instants from the specified source truncated to
120      * the nearest occurrence of the specified duration.
121      * <p>
122      * This source will only tick as per the specified duration. Thus, if the
123      * duration is half a second, the source will return instants truncated to the
124      * half second.
125      * <p>
126      * The tick duration must be positive. If it has a part smaller than a whole
127      * millisecond, then the whole duration must divide into one second without
128      * leaving a remainder. All normal tick durations will match these criteria,
129      * including any multiple of hours, minutes, seconds and milliseconds, and
130      * sensible nanosecond durations, such as 20ns, 250,000ns and 500,000ns.
131      * <p>
132      * A duration of zero or one nanosecond would have no truncation effect. Passing
133      * one of these will return the underlying source.
134      * <p>
135      * Implementations may use a caching strategy for performance reasons. As such,
136      * it is possible that the start of the requested duration observed via this
137      * source will be later than that observed directly via the underlying source.
138      * <p>
139      * The returned implementation is immutable, thread-safe and
140      * {@code Serializable} providing that the base source is.
141      *
142      * @param baseSource  the base source to base the ticking source on, not null
143      * @param tickDuration  the duration of each visible tick, not negative, not null
144      * @return a source that ticks in whole units of the duration, not null
145      * @throws IllegalArgumentException if the duration is negative, or has a
146      *  part smaller than a whole millisecond such that the whole duration is not
147      *  divisible into one second
148      * @throws ArithmeticException if the duration is too large to be represented as nanos
149      */
tick(InstantSource baseSource, Duration tickDuration)150     static InstantSource tick(InstantSource baseSource, Duration tickDuration) {
151         Objects.requireNonNull(baseSource, "baseSource");
152         return Clock.tick(baseSource.withZone(ZoneOffset.UTC), tickDuration);
153     }
154 
155     //-----------------------------------------------------------------------
156     /**
157      * Obtains a source that always returns the same instant.
158      * <p>
159      * This source simply returns the specified instant.
160      * As such, it is not a source that represents the current instant.
161      * The main use case for this is in testing, where the fixed source ensures
162      * tests are not dependent on the current source.
163      * <p>
164      * The returned implementation is immutable, thread-safe and {@code Serializable}.
165      *
166      * @param fixedInstant  the instant to use, not null
167      * @return a source that always returns the same instant, not null
168      */
fixed(Instant fixedInstant)169     static InstantSource fixed(Instant fixedInstant) {
170         return Clock.fixed(fixedInstant, ZoneOffset.UTC);
171     }
172 
173     //-------------------------------------------------------------------------
174     /**
175      * Obtains a source that returns instants from the specified source with the
176      * specified duration added.
177      * <p>
178      * This source wraps another source, returning instants that are later by the
179      * specified duration. If the duration is negative, the instants will be
180      * earlier than the current date and time.
181      * The main use case for this is to simulate running in the future or in the past.
182      * <p>
183      * A duration of zero would have no offsetting effect.
184      * Passing zero will return the underlying source.
185      * <p>
186      * The returned implementation is immutable, thread-safe and {@code Serializable}
187      * providing that the base source is.
188      *
189      * @param baseSource  the base source to add the duration to, not null
190      * @param offsetDuration  the duration to add, not null
191      * @return a source based on the base source with the duration added, not null
192      */
offset(InstantSource baseSource, Duration offsetDuration)193     static InstantSource offset(InstantSource baseSource, Duration offsetDuration) {
194         Objects.requireNonNull(baseSource, "baseSource");
195         return Clock.offset(baseSource.withZone(ZoneOffset.UTC), offsetDuration);
196     }
197 
198     //-----------------------------------------------------------------------
199     /**
200      * Gets the current instant of the source.
201      * <p>
202      * This returns an instant representing the current instant as defined by the source.
203      *
204      * @return the current instant from this source, not null
205      * @throws DateTimeException if the instant cannot be obtained, not thrown by most implementations
206      */
instant()207     Instant instant();
208 
209     //-------------------------------------------------------------------------
210     /**
211      * Gets the current millisecond instant of the source.
212      * <p>
213      * This returns the millisecond-based instant, measured from 1970-01-01T00:00Z (UTC).
214      * This is equivalent to the definition of {@link System#currentTimeMillis()}.
215      * <p>
216      * Most applications should avoid this method and use {@link Instant} to represent
217      * an instant on the time-line rather than a raw millisecond value.
218      * This method is provided to allow the use of the source in high performance use cases
219      * where the creation of an object would be unacceptable.
220      *
221      * @implSpec
222      * The default implementation calls {@link #instant()}.
223      *
224      * @return the current millisecond instant from this source, measured from
225      *  the Java epoch of 1970-01-01T00:00Z (UTC), not null
226      * @throws DateTimeException if the instant cannot be obtained, not thrown by most implementations
227      */
millis()228     default long millis() {
229         return instant().toEpochMilli();
230     }
231 
232     //-----------------------------------------------------------------------
233     /**
234      * Returns a clock with the specified time-zone.
235      * <p>
236      * This returns a {@link Clock}, which is an extension of this interface
237      * that combines this source and the specified time-zone.
238      * <p>
239      * The returned implementation is immutable, thread-safe and {@code Serializable}
240      * providing that this source is.
241      *
242      * @implSpec
243      * The default implementation returns an immutable, thread-safe and
244      * {@code Serializable} subclass of {@link Clock} that combines this
245      * source and the specified zone.
246      *
247      * @param zone  the time-zone to use, not null
248      * @return a clock based on this source with the specified time-zone, not null
249      */
withZone(ZoneId zone)250     default Clock withZone(ZoneId zone) {
251         return new SourceClock(this, zone);
252     }
253 
254 }
255