Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/Clock.java
38829 views
/*1* Copyright (c) 2012, 2013, 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*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time;6263import static java.time.LocalTime.NANOS_PER_MINUTE;64import static java.time.LocalTime.NANOS_PER_SECOND;6566import java.io.Serializable;67import java.util.Objects;68import java.util.TimeZone;6970/**71* A clock providing access to the current instant, date and time using a time-zone.72* <p>73* Instances of this class are used to find the current instant, which can be74* interpreted using the stored time-zone to find the current date and time.75* As such, a clock can be used instead of {@link System#currentTimeMillis()}76* and {@link TimeZone#getDefault()}.77* <p>78* Use of a {@code Clock} is optional. All key date-time classes also have a79* {@code now()} factory method that uses the system clock in the default time zone.80* The primary purpose of this abstraction is to allow alternate clocks to be81* plugged in as and when required. Applications use an object to obtain the82* current time rather than a static method. This can simplify testing.83* <p>84* Best practice for applications is to pass a {@code Clock} into any method85* that requires the current instant. A dependency injection framework is one86* way to achieve this:87* <pre>88* public class MyBean {89* private Clock clock; // dependency inject90* ...91* public void process(LocalDate eventDate) {92* if (eventDate.isBefore(LocalDate.now(clock)) {93* ...94* }95* }96* }97* </pre>98* This approach allows an alternate clock, such as {@link #fixed(Instant, ZoneId) fixed}99* or {@link #offset(Clock, Duration) offset} to be used during testing.100* <p>101* The {@code system} factory methods provide clocks based on the best available102* system clock This may use {@link System#currentTimeMillis()}, or a higher103* resolution clock if one is available.104*105* @implSpec106* This abstract class must be implemented with care to ensure other classes operate correctly.107* All implementations that can be instantiated must be final, immutable and thread-safe.108* <p>109* The principal methods are defined to allow the throwing of an exception.110* In normal use, no exceptions will be thrown, however one possible implementation would be to111* obtain the time from a central time server across the network. Obviously, in this case the112* lookup could fail, and so the method is permitted to throw an exception.113* <p>114* The returned instants from {@code Clock} work on a time-scale that ignores leap seconds,115* as described in {@link Instant}. If the implementation wraps a source that provides leap116* second information, then a mechanism should be used to "smooth" the leap second.117* The Java Time-Scale mandates the use of UTC-SLS, however clock implementations may choose118* how accurate they are with the time-scale so long as they document how they work.119* Implementations are therefore not required to actually perform the UTC-SLS slew or to120* otherwise be aware of leap seconds.121* <p>122* Implementations should implement {@code Serializable} wherever possible and must123* document whether or not they do support serialization.124*125* @implNote126* The clock implementation provided here is based on {@link System#currentTimeMillis()}.127* That method provides little to no guarantee about the accuracy of the clock.128* Applications requiring a more accurate clock must implement this abstract class129* themselves using a different external clock, such as an NTP server.130*131* @since 1.8132*/133public abstract class Clock {134135/**136* Obtains a clock that returns the current instant using the best available137* system clock, converting to date and time using the UTC time-zone.138* <p>139* This clock, rather than {@link #systemDefaultZone()}, should be used when140* you need the current instant without the date or time.141* <p>142* This clock is based on the best available system clock.143* This may use {@link System#currentTimeMillis()}, or a higher resolution144* clock if one is available.145* <p>146* Conversion from instant to date or time uses the {@linkplain ZoneOffset#UTC UTC time-zone}.147* <p>148* The returned implementation is immutable, thread-safe and {@code Serializable}.149* It is equivalent to {@code system(ZoneOffset.UTC)}.150*151* @return a clock that uses the best available system clock in the UTC zone, not null152*/153public static Clock systemUTC() {154return new SystemClock(ZoneOffset.UTC);155}156157/**158* Obtains a clock that returns the current instant using the best available159* system clock, converting to date and time using the default time-zone.160* <p>161* This clock is based on the best available system clock.162* This may use {@link System#currentTimeMillis()}, or a higher resolution163* clock if one is available.164* <p>165* Using this method hard codes a dependency to the default time-zone into your application.166* It is recommended to avoid this and use a specific time-zone whenever possible.167* The {@link #systemUTC() UTC clock} should be used when you need the current instant168* without the date or time.169* <p>170* The returned implementation is immutable, thread-safe and {@code Serializable}.171* It is equivalent to {@code system(ZoneId.systemDefault())}.172*173* @return a clock that uses the best available system clock in the default zone, not null174* @see ZoneId#systemDefault()175*/176public static Clock systemDefaultZone() {177return new SystemClock(ZoneId.systemDefault());178}179180/**181* Obtains a clock that returns the current instant using best available182* system clock.183* <p>184* This clock is based on the best available system clock.185* This may use {@link System#currentTimeMillis()}, or a higher resolution186* clock if one is available.187* <p>188* Conversion from instant to date or time uses the specified time-zone.189* <p>190* The returned implementation is immutable, thread-safe and {@code Serializable}.191*192* @param zone the time-zone to use to convert the instant to date-time, not null193* @return a clock that uses the best available system clock in the specified zone, not null194*/195public static Clock system(ZoneId zone) {196Objects.requireNonNull(zone, "zone");197return new SystemClock(zone);198}199200//-------------------------------------------------------------------------201/**202* Obtains a clock that returns the current instant ticking in whole seconds203* using best available system clock.204* <p>205* This clock will always have the nano-of-second field set to zero.206* This ensures that the visible time ticks in whole seconds.207* The underlying clock is the best available system clock, equivalent to208* using {@link #system(ZoneId)}.209* <p>210* Implementations may use a caching strategy for performance reasons.211* As such, it is possible that the start of the second observed via this212* clock will be later than that observed directly via the underlying clock.213* <p>214* The returned implementation is immutable, thread-safe and {@code Serializable}.215* It is equivalent to {@code tick(system(zone), Duration.ofSeconds(1))}.216*217* @param zone the time-zone to use to convert the instant to date-time, not null218* @return a clock that ticks in whole seconds using the specified zone, not null219*/220public static Clock tickSeconds(ZoneId zone) {221return new TickClock(system(zone), NANOS_PER_SECOND);222}223224/**225* Obtains a clock that returns the current instant ticking in whole minutes226* using best available system clock.227* <p>228* This clock will always have the nano-of-second and second-of-minute fields set to zero.229* This ensures that the visible time ticks in whole minutes.230* The underlying clock is the best available system clock, equivalent to231* using {@link #system(ZoneId)}.232* <p>233* Implementations may use a caching strategy for performance reasons.234* As such, it is possible that the start of the minute observed via this235* clock will be later than that observed directly via the underlying clock.236* <p>237* The returned implementation is immutable, thread-safe and {@code Serializable}.238* It is equivalent to {@code tick(system(zone), Duration.ofMinutes(1))}.239*240* @param zone the time-zone to use to convert the instant to date-time, not null241* @return a clock that ticks in whole minutes using the specified zone, not null242*/243public static Clock tickMinutes(ZoneId zone) {244return new TickClock(system(zone), NANOS_PER_MINUTE);245}246247/**248* Obtains a clock that returns instants from the specified clock truncated249* to the nearest occurrence of the specified duration.250* <p>251* This clock will only tick as per the specified duration. Thus, if the duration252* is half a second, the clock will return instants truncated to the half second.253* <p>254* The tick duration must be positive. If it has a part smaller than a whole255* millisecond, then the whole duration must divide into one second without256* leaving a remainder. All normal tick durations will match these criteria,257* including any multiple of hours, minutes, seconds and milliseconds, and258* sensible nanosecond durations, such as 20ns, 250,000ns and 500,000ns.259* <p>260* A duration of zero or one nanosecond would have no truncation effect.261* Passing one of these will return the underlying clock.262* <p>263* Implementations may use a caching strategy for performance reasons.264* As such, it is possible that the start of the requested duration observed265* via this clock will be later than that observed directly via the underlying clock.266* <p>267* The returned implementation is immutable, thread-safe and {@code Serializable}268* providing that the base clock is.269*270* @param baseClock the base clock to base the ticking clock on, not null271* @param tickDuration the duration of each visible tick, not negative, not null272* @return a clock that ticks in whole units of the duration, not null273* @throws IllegalArgumentException if the duration is negative, or has a274* part smaller than a whole millisecond such that the whole duration is not275* divisible into one second276* @throws ArithmeticException if the duration is too large to be represented as nanos277*/278public static Clock tick(Clock baseClock, Duration tickDuration) {279Objects.requireNonNull(baseClock, "baseClock");280Objects.requireNonNull(tickDuration, "tickDuration");281if (tickDuration.isNegative()) {282throw new IllegalArgumentException("Tick duration must not be negative");283}284long tickNanos = tickDuration.toNanos();285if (tickNanos % 1000_000 == 0) {286// ok, no fraction of millisecond287} else if (1000_000_000 % tickNanos == 0) {288// ok, divides into one second without remainder289} else {290throw new IllegalArgumentException("Invalid tick duration");291}292if (tickNanos <= 1) {293return baseClock;294}295return new TickClock(baseClock, tickNanos);296}297298//-----------------------------------------------------------------------299/**300* Obtains a clock that always returns the same instant.301* <p>302* This clock simply returns the specified instant.303* As such, it is not a clock in the conventional sense.304* The main use case for this is in testing, where the fixed clock ensures305* tests are not dependent on the current clock.306* <p>307* The returned implementation is immutable, thread-safe and {@code Serializable}.308*309* @param fixedInstant the instant to use as the clock, not null310* @param zone the time-zone to use to convert the instant to date-time, not null311* @return a clock that always returns the same instant, not null312*/313public static Clock fixed(Instant fixedInstant, ZoneId zone) {314Objects.requireNonNull(fixedInstant, "fixedInstant");315Objects.requireNonNull(zone, "zone");316return new FixedClock(fixedInstant, zone);317}318319//-------------------------------------------------------------------------320/**321* Obtains a clock that returns instants from the specified clock with the322* specified duration added323* <p>324* This clock wraps another clock, returning instants that are later by the325* specified duration. If the duration is negative, the instants will be326* earlier than the current date and time.327* The main use case for this is to simulate running in the future or in the past.328* <p>329* A duration of zero would have no offsetting effect.330* Passing zero will return the underlying clock.331* <p>332* The returned implementation is immutable, thread-safe and {@code Serializable}333* providing that the base clock is.334*335* @param baseClock the base clock to add the duration to, not null336* @param offsetDuration the duration to add, not null337* @return a clock based on the base clock with the duration added, not null338*/339public static Clock offset(Clock baseClock, Duration offsetDuration) {340Objects.requireNonNull(baseClock, "baseClock");341Objects.requireNonNull(offsetDuration, "offsetDuration");342if (offsetDuration.equals(Duration.ZERO)) {343return baseClock;344}345return new OffsetClock(baseClock, offsetDuration);346}347348//-----------------------------------------------------------------------349/**350* Constructor accessible by subclasses.351*/352protected Clock() {353}354355//-----------------------------------------------------------------------356/**357* Gets the time-zone being used to create dates and times.358* <p>359* A clock will typically obtain the current instant and then convert that360* to a date or time using a time-zone. This method returns the time-zone used.361*362* @return the time-zone being used to interpret instants, not null363*/364public abstract ZoneId getZone();365366/**367* Returns a copy of this clock with a different time-zone.368* <p>369* A clock will typically obtain the current instant and then convert that370* to a date or time using a time-zone. This method returns a clock with371* similar properties but using a different time-zone.372*373* @param zone the time-zone to change to, not null374* @return a clock based on this clock with the specified time-zone, not null375*/376public abstract Clock withZone(ZoneId zone);377378//-------------------------------------------------------------------------379/**380* Gets the current millisecond instant of the clock.381* <p>382* This returns the millisecond-based instant, measured from 1970-01-01T00:00Z (UTC).383* This is equivalent to the definition of {@link System#currentTimeMillis()}.384* <p>385* Most applications should avoid this method and use {@link Instant} to represent386* an instant on the time-line rather than a raw millisecond value.387* This method is provided to allow the use of the clock in high performance use cases388* where the creation of an object would be unacceptable.389* <p>390* The default implementation currently calls {@link #instant}.391*392* @return the current millisecond instant from this clock, measured from393* the Java epoch of 1970-01-01T00:00Z (UTC), not null394* @throws DateTimeException if the instant cannot be obtained, not thrown by most implementations395*/396public long millis() {397return instant().toEpochMilli();398}399400//-----------------------------------------------------------------------401/**402* Gets the current instant of the clock.403* <p>404* This returns an instant representing the current instant as defined by the clock.405*406* @return the current instant from this clock, not null407* @throws DateTimeException if the instant cannot be obtained, not thrown by most implementations408*/409public abstract Instant instant();410411//-----------------------------------------------------------------------412/**413* Checks if this clock is equal to another clock.414* <p>415* Clocks should override this method to compare equals based on416* their state and to meet the contract of {@link Object#equals}.417* If not overridden, the behavior is defined by {@link Object#equals}418*419* @param obj the object to check, null returns false420* @return true if this is equal to the other clock421*/422@Override423public boolean equals(Object obj) {424return super.equals(obj);425}426427/**428* A hash code for this clock.429* <p>430* Clocks should override this method based on431* their state and to meet the contract of {@link Object#hashCode}.432* If not overridden, the behavior is defined by {@link Object#hashCode}433*434* @return a suitable hash code435*/436@Override437public int hashCode() {438return super.hashCode();439}440441//-----------------------------------------------------------------------442/**443* Implementation of a clock that always returns the latest time from444* {@link System#currentTimeMillis()}.445*/446static final class SystemClock extends Clock implements Serializable {447private static final long serialVersionUID = 6740630888130243051L;448private final ZoneId zone;449450SystemClock(ZoneId zone) {451this.zone = zone;452}453@Override454public ZoneId getZone() {455return zone;456}457@Override458public Clock withZone(ZoneId zone) {459if (zone.equals(this.zone)) { // intentional NPE460return this;461}462return new SystemClock(zone);463}464@Override465public long millis() {466return System.currentTimeMillis();467}468@Override469public Instant instant() {470return Instant.ofEpochMilli(millis());471}472@Override473public boolean equals(Object obj) {474if (obj instanceof SystemClock) {475return zone.equals(((SystemClock) obj).zone);476}477return false;478}479@Override480public int hashCode() {481return zone.hashCode() + 1;482}483@Override484public String toString() {485return "SystemClock[" + zone + "]";486}487}488489//-----------------------------------------------------------------------490/**491* Implementation of a clock that always returns the same instant.492* This is typically used for testing.493*/494static final class FixedClock extends Clock implements Serializable {495private static final long serialVersionUID = 7430389292664866958L;496private final Instant instant;497private final ZoneId zone;498499FixedClock(Instant fixedInstant, ZoneId zone) {500this.instant = fixedInstant;501this.zone = zone;502}503@Override504public ZoneId getZone() {505return zone;506}507@Override508public Clock withZone(ZoneId zone) {509if (zone.equals(this.zone)) { // intentional NPE510return this;511}512return new FixedClock(instant, zone);513}514@Override515public long millis() {516return instant.toEpochMilli();517}518@Override519public Instant instant() {520return instant;521}522@Override523public boolean equals(Object obj) {524if (obj instanceof FixedClock) {525FixedClock other = (FixedClock) obj;526return instant.equals(other.instant) && zone.equals(other.zone);527}528return false;529}530@Override531public int hashCode() {532return instant.hashCode() ^ zone.hashCode();533}534@Override535public String toString() {536return "FixedClock[" + instant + "," + zone + "]";537}538}539540//-----------------------------------------------------------------------541/**542* Implementation of a clock that adds an offset to an underlying clock.543*/544static final class OffsetClock extends Clock implements Serializable {545private static final long serialVersionUID = 2007484719125426256L;546private final Clock baseClock;547private final Duration offset;548549OffsetClock(Clock baseClock, Duration offset) {550this.baseClock = baseClock;551this.offset = offset;552}553@Override554public ZoneId getZone() {555return baseClock.getZone();556}557@Override558public Clock withZone(ZoneId zone) {559if (zone.equals(baseClock.getZone())) { // intentional NPE560return this;561}562return new OffsetClock(baseClock.withZone(zone), offset);563}564@Override565public long millis() {566return Math.addExact(baseClock.millis(), offset.toMillis());567}568@Override569public Instant instant() {570return baseClock.instant().plus(offset);571}572@Override573public boolean equals(Object obj) {574if (obj instanceof OffsetClock) {575OffsetClock other = (OffsetClock) obj;576return baseClock.equals(other.baseClock) && offset.equals(other.offset);577}578return false;579}580@Override581public int hashCode() {582return baseClock.hashCode() ^ offset.hashCode();583}584@Override585public String toString() {586return "OffsetClock[" + baseClock + "," + offset + "]";587}588}589590//-----------------------------------------------------------------------591/**592* Implementation of a clock that adds an offset to an underlying clock.593*/594static final class TickClock extends Clock implements Serializable {595private static final long serialVersionUID = 6504659149906368850L;596private final Clock baseClock;597private final long tickNanos;598599TickClock(Clock baseClock, long tickNanos) {600this.baseClock = baseClock;601this.tickNanos = tickNanos;602}603@Override604public ZoneId getZone() {605return baseClock.getZone();606}607@Override608public Clock withZone(ZoneId zone) {609if (zone.equals(baseClock.getZone())) { // intentional NPE610return this;611}612return new TickClock(baseClock.withZone(zone), tickNanos);613}614@Override615public long millis() {616long millis = baseClock.millis();617return millis - Math.floorMod(millis, tickNanos / 1000_000L);618}619@Override620public Instant instant() {621if ((tickNanos % 1000_000) == 0) {622long millis = baseClock.millis();623return Instant.ofEpochMilli(millis - Math.floorMod(millis, tickNanos / 1000_000L));624}625Instant instant = baseClock.instant();626long nanos = instant.getNano();627long adjust = Math.floorMod(nanos, tickNanos);628return instant.minusNanos(adjust);629}630@Override631public boolean equals(Object obj) {632if (obj instanceof TickClock) {633TickClock other = (TickClock) obj;634return baseClock.equals(other.baseClock) && tickNanos == other.tickNanos;635}636return false;637}638@Override639public int hashCode() {640return baseClock.hashCode() ^ ((int) (tickNanos ^ (tickNanos >>> 32)));641}642@Override643public String toString() {644return "TickClock[" + baseClock + "," + Duration.ofNanos(tickNanos) + "]";645}646}647648}649650651