Path: blob/master/src/java.base/share/classes/java/time/InstantSource.java
67794 views
/*1* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package java.time;2526import java.time.Clock.SourceClock;27import java.time.Clock.SystemInstantSource;28import java.util.Objects;2930/**31* Provides access to the current instant.32* <p>33* Instances of this interface are used to access a pluggable representation of the current instant.34* For example, {@code InstantSource} can be used instead of {@link System#currentTimeMillis()}.35* <p>36* The primary purpose of this abstraction is to allow alternate instant sources to be37* plugged in as and when required. Applications use an object to obtain the38* current time rather than a static method. This can simplify testing.39* <p>40* As such, this interface does not guarantee the result actually represents the current instant41* on the time-line. Instead, it allows the application to provide a controlled view as to what42* the current instant is.43* <p>44* Best practice for applications is to pass an {@code InstantSource} into any method45* that requires the current instant. A dependency injection framework is one46* way to achieve this:47* <pre>48* public class MyBean {49* private InstantSource source; // dependency inject50* ...51* public void process(Instant endInstant) {52* if (source.instant().isAfter(endInstant) {53* ...54* }55* }56* }57* </pre>58* This approach allows an alternative source, such as {@link #fixed(Instant) fixed}59* or {@link #offset(InstantSource, Duration) offset} to be used during testing.60* <p>61* The {@code system} factory method provides a source based on the best available62* system clock. This may use {@link System#currentTimeMillis()}, or a higher63* resolution clock if one is available.64*65* @implSpec66* This interface must be implemented with care to ensure other classes operate correctly.67* All implementations must be thread-safe - a single instance must be capable of be invoked68* from multiple threads without negative consequences such as race conditions.69* <p>70* The principal methods are defined to allow the throwing of an exception.71* In normal use, no exceptions will be thrown, however one possible implementation would be to72* obtain the time from a central time server across the network. Obviously, in this case the73* lookup could fail, and so the method is permitted to throw an exception.74* <p>75* The returned instants from {@code InstantSource} work on a time-scale that ignores leap seconds,76* as described in {@link Instant}. If the implementation wraps a source that provides leap77* second information, then a mechanism should be used to "smooth" the leap second.78* The Java Time-Scale mandates the use of UTC-SLS, however implementations may choose79* how accurate they are with the time-scale so long as they document how they work.80* Implementations are therefore not required to actually perform the UTC-SLS slew or to81* otherwise be aware of leap seconds.82* <p>83* Implementations should implement {@code Serializable} wherever possible and must84* document whether or not they do support serialization.85*86* @implNote87* The implementation provided here is based on the same underlying system clock88* as {@link System#currentTimeMillis()}, but may have a precision finer than89* milliseconds if available.90* However, little to no guarantee is provided about the accuracy of the91* underlying system clock. Applications requiring a more accurate system clock must92* implement this abstract class themselves using a different external system clock,93* such as an NTP server.94*95* @since 1796*/97public interface InstantSource {9899/**100* Obtains a source that returns the current instant using the best available101* system clock.102* <p>103* This source is based on the best available system clock. This may use104* {@link System#currentTimeMillis()}, or a higher resolution system clock if105* one is available.106* <p>107* The returned implementation is immutable, thread-safe and108* {@code Serializable}.109*110* @return a source that uses the best available system clock, not null111*/112static InstantSource system() {113return SystemInstantSource.INSTANCE;114}115116//-------------------------------------------------------------------------117/**118* Obtains a source that returns instants from the specified source truncated to119* the nearest occurrence of the specified duration.120* <p>121* This source will only tick as per the specified duration. Thus, if the122* duration is half a second, the source will return instants truncated to the123* half second.124* <p>125* The tick duration must be positive. If it has a part smaller than a whole126* millisecond, then the whole duration must divide into one second without127* leaving a remainder. All normal tick durations will match these criteria,128* including any multiple of hours, minutes, seconds and milliseconds, and129* sensible nanosecond durations, such as 20ns, 250,000ns and 500,000ns.130* <p>131* A duration of zero or one nanosecond would have no truncation effect. Passing132* one of these will return the underlying source.133* <p>134* Implementations may use a caching strategy for performance reasons. As such,135* it is possible that the start of the requested duration observed via this136* source will be later than that observed directly via the underlying source.137* <p>138* The returned implementation is immutable, thread-safe and139* {@code Serializable} providing that the base source is.140*141* @param baseSource the base source to base the ticking source on, not null142* @param tickDuration the duration of each visible tick, not negative, not null143* @return a source that ticks in whole units of the duration, not null144* @throws IllegalArgumentException if the duration is negative, or has a145* part smaller than a whole millisecond such that the whole duration is not146* divisible into one second147* @throws ArithmeticException if the duration is too large to be represented as nanos148*/149static InstantSource tick(InstantSource baseSource, Duration tickDuration) {150Objects.requireNonNull(baseSource, "baseSource");151return Clock.tick(baseSource.withZone(ZoneOffset.UTC), tickDuration);152}153154//-----------------------------------------------------------------------155/**156* Obtains a source that always returns the same instant.157* <p>158* This source simply returns the specified instant.159* As such, it is not a source that represents the current instant.160* The main use case for this is in testing, where the fixed source ensures161* tests are not dependent on the current source.162* <p>163* The returned implementation is immutable, thread-safe and {@code Serializable}.164*165* @param fixedInstant the instant to use, not null166* @return a source that always returns the same instant, not null167*/168static InstantSource fixed(Instant fixedInstant) {169return Clock.fixed(fixedInstant, ZoneOffset.UTC);170}171172//-------------------------------------------------------------------------173/**174* Obtains a source that returns instants from the specified source with the175* specified duration added.176* <p>177* This source wraps another source, returning instants that are later by the178* specified duration. If the duration is negative, the instants will be179* earlier than the current date and time.180* The main use case for this is to simulate running in the future or in the past.181* <p>182* A duration of zero would have no offsetting effect.183* Passing zero will return the underlying source.184* <p>185* The returned implementation is immutable, thread-safe and {@code Serializable}186* providing that the base source is.187*188* @param baseSource the base source to add the duration to, not null189* @param offsetDuration the duration to add, not null190* @return a source based on the base source with the duration added, not null191*/192static InstantSource offset(InstantSource baseSource, Duration offsetDuration) {193Objects.requireNonNull(baseSource, "baseSource");194return Clock.offset(baseSource.withZone(ZoneOffset.UTC), offsetDuration);195}196197//-----------------------------------------------------------------------198/**199* Gets the current instant of the source.200* <p>201* This returns an instant representing the current instant as defined by the source.202*203* @return the current instant from this source, not null204* @throws DateTimeException if the instant cannot be obtained, not thrown by most implementations205*/206Instant instant();207208//-------------------------------------------------------------------------209/**210* Gets the current millisecond instant of the source.211* <p>212* This returns the millisecond-based instant, measured from 1970-01-01T00:00Z (UTC).213* This is equivalent to the definition of {@link System#currentTimeMillis()}.214* <p>215* Most applications should avoid this method and use {@link Instant} to represent216* an instant on the time-line rather than a raw millisecond value.217* This method is provided to allow the use of the source in high performance use cases218* where the creation of an object would be unacceptable.219*220* @implSpec221* The default implementation calls {@link #instant()}.222*223* @return the current millisecond instant from this source, measured from224* the Java epoch of 1970-01-01T00:00Z (UTC), not null225* @throws DateTimeException if the instant cannot be obtained, not thrown by most implementations226*/227default long millis() {228return instant().toEpochMilli();229}230231//-----------------------------------------------------------------------232/**233* Returns a clock with the specified time-zone.234* <p>235* This returns a {@link Clock}, which is an extension of this interface236* that combines this source and the specified time-zone.237* <p>238* The returned implementation is immutable, thread-safe and {@code Serializable}239* providing that this source is.240*241* @implSpec242* The default implementation returns an immutable, thread-safe and243* {@code Serializable} subclass of {@link Clock} that combines this244* source and the specified zone.245*246* @param zone the time-zone to use, not null247* @return a clock based on this source with the specified time-zone, not null248*/249default Clock withZone(ZoneId zone) {250return new SourceClock(this, zone);251}252253}254255256