1 /* 2 * Copyright (c) 2012, 2015, 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 26 /* 27 * This file is available under and governed by the GNU General Public 28 * License version 2 only, as published by the Free Software Foundation. 29 * However, the following notice accompanied the original version of this 30 * file: 31 * 32 * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos 33 * 34 * All rights reserved. 35 * 36 * Redistribution and use in source and binary forms, with or without 37 * modification, are permitted provided that the following conditions are met: 38 * 39 * * Redistributions of source code must retain the above copyright notice, 40 * this list of conditions and the following disclaimer. 41 * 42 * * Redistributions in binary form must reproduce the above copyright notice, 43 * this list of conditions and the following disclaimer in the documentation 44 * and/or other materials provided with the distribution. 45 * 46 * * Neither the name of JSR-310 nor the names of its contributors 47 * may be used to endorse or promote products derived from this software 48 * without specific prior written permission. 49 * 50 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 51 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 52 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 53 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 54 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 55 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 56 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 57 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 58 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 59 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 60 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 61 */ 62 package java.time; 63 64 import java.io.IOException; 65 import java.io.ObjectInputStream; 66 import static java.time.LocalTime.NANOS_PER_MINUTE; 67 import static java.time.LocalTime.NANOS_PER_SECOND; 68 69 import java.io.Serializable; 70 import java.util.Objects; 71 import java.util.TimeZone; 72 import sun.misc.VM; 73 74 /** 75 * A clock providing access to the current instant, date and time using a time-zone. 76 * <p> 77 * Instances of this class are used to find the current instant, which can be 78 * interpreted using the stored time-zone to find the current date and time. 79 * As such, a clock can be used instead of {@link System#currentTimeMillis()} 80 * and {@link TimeZone#getDefault()}. 81 * <p> 82 * Use of a {@code Clock} is optional. All key date-time classes also have a 83 * {@code now()} factory method that uses the system clock in the default time zone. 84 * The primary purpose of this abstraction is to allow alternate clocks to be 85 * plugged in as and when required. Applications use an object to obtain the 86 * current time rather than a static method. This can simplify testing. 87 * <p> 88 * Best practice for applications is to pass a {@code Clock} into any method 89 * that requires the current instant. A dependency injection framework is one 90 * way to achieve this: 91 * <pre> 92 * public class MyBean { 93 * private Clock clock; // dependency inject 94 * ... 95 * public void process(LocalDate eventDate) { 96 * if (eventDate.isBefore(LocalDate.now(clock)) { 97 * ... 98 * } 99 * } 100 * } 101 * </pre> 102 * This approach allows an alternate clock, such as {@link #fixed(Instant, ZoneId) fixed} 103 * or {@link #offset(Clock, Duration) offset} to be used during testing. 104 * <p> 105 * The {@code system} factory methods provide clocks based on the best available 106 * system clock This may use {@link System#currentTimeMillis()}, or a higher 107 * resolution clock if one is available. 108 * 109 * @implSpec 110 * This abstract class must be implemented with care to ensure other classes operate correctly. 111 * All implementations that can be instantiated must be final, immutable and thread-safe. 112 * <p> 113 * The principal methods are defined to allow the throwing of an exception. 114 * In normal use, no exceptions will be thrown, however one possible implementation would be to 115 * obtain the time from a central time server across the network. Obviously, in this case the 116 * lookup could fail, and so the method is permitted to throw an exception. 117 * <p> 118 * The returned instants from {@code Clock} work on a time-scale that ignores leap seconds, 119 * as described in {@link Instant}. If the implementation wraps a source that provides leap 120 * second information, then a mechanism should be used to "smooth" the leap second. 121 * The Java Time-Scale mandates the use of UTC-SLS, however clock implementations may choose 122 * how accurate they are with the time-scale so long as they document how they work. 123 * Implementations are therefore not required to actually perform the UTC-SLS slew or to 124 * otherwise be aware of leap seconds. 125 * <p> 126 * Implementations should implement {@code Serializable} wherever possible and must 127 * document whether or not they do support serialization. 128 * 129 * @implNote 130 * The clock implementation provided here is based on {@link System#currentTimeMillis()}. 131 * That method provides little to no guarantee about the accuracy of the clock. 132 * Applications requiring a more accurate clock must implement this abstract class 133 * themselves using a different external clock, such as an NTP server. 134 * 135 * @since 1.8 136 */ 137 public abstract class Clock { 138 139 /** 140 * Obtains a clock that returns the current instant using the best available 141 * system clock, converting to date and time using the UTC time-zone. 142 * <p> 143 * This clock, rather than {@link #systemDefaultZone()}, should be used when 144 * you need the current instant without the date or time. 145 * <p> 146 * This clock is based on the best available system clock. 147 * This may use {@link System#currentTimeMillis()}, or a higher resolution 148 * clock if one is available. 149 * <p> 150 * Conversion from instant to date or time uses the {@linkplain ZoneOffset#UTC UTC time-zone}. 151 * <p> 152 * The returned implementation is immutable, thread-safe and {@code Serializable}. 153 * It is equivalent to {@code system(ZoneOffset.UTC)}. 154 * 155 * @return a clock that uses the best available system clock in the UTC zone, not null 156 */ 157 public static Clock systemUTC() { 158 return new SystemClock(ZoneOffset.UTC); 159 } 160 161 /** 162 * Obtains a clock that returns the current instant using the best available 163 * system clock, converting to date and time using the default time-zone. 164 * <p> 165 * This clock is based on the best available system clock. 166 * This may use {@link System#currentTimeMillis()}, or a higher resolution 167 * clock if one is available. 168 * <p> 169 * Using this method hard codes a dependency to the default time-zone into your application. 170 * It is recommended to avoid this and use a specific time-zone whenever possible. 171 * The {@link #systemUTC() UTC clock} should be used when you need the current instant 172 * without the date or time. 173 * <p> 174 * The returned implementation is immutable, thread-safe and {@code Serializable}. 175 * It is equivalent to {@code system(ZoneId.systemDefault())}. 176 * 177 * @return a clock that uses the best available system clock in the default zone, not null 178 * @see ZoneId#systemDefault() 179 */ 180 public static Clock systemDefaultZone() { 181 return new SystemClock(ZoneId.systemDefault()); 182 } 183 184 /** 185 * Obtains a clock that returns the current instant using best available 186 * system clock. 187 * <p> 188 * This clock is based on the best available system clock. 189 * This may use {@link System#currentTimeMillis()}, or a higher resolution 190 * clock if one is available. 191 * <p> 192 * Conversion from instant to date or time uses the specified time-zone. 193 * <p> 194 * The returned implementation is immutable, thread-safe and {@code Serializable}. 195 * 196 * @param zone the time-zone to use to convert the instant to date-time, not null 197 * @return a clock that uses the best available system clock in the specified zone, not null 198 */ 199 public static Clock system(ZoneId zone) { 200 Objects.requireNonNull(zone, "zone"); 201 return new SystemClock(zone); 202 } 203 204 //------------------------------------------------------------------------- 205 /** 206 * Obtains a clock that returns the current instant ticking in whole seconds 207 * using best available system clock. 208 * <p> 209 * This clock will always have the nano-of-second field set to zero. 210 * This ensures that the visible time ticks in whole seconds. 211 * The underlying clock is the best available system clock, equivalent to 212 * using {@link #system(ZoneId)}. 213 * <p> 214 * Implementations may use a caching strategy for performance reasons. 215 * As such, it is possible that the start of the second observed via this 216 * clock will be later than that observed directly via the underlying clock. 217 * <p> 218 * The returned implementation is immutable, thread-safe and {@code Serializable}. 219 * It is equivalent to {@code tick(system(zone), Duration.ofSeconds(1))}. 220 * 221 * @param zone the time-zone to use to convert the instant to date-time, not null 222 * @return a clock that ticks in whole seconds using the specified zone, not null 223 */ 224 public static Clock tickSeconds(ZoneId zone) { 225 return new TickClock(system(zone), NANOS_PER_SECOND); 226 } 227 228 /** 229 * Obtains a clock that returns the current instant ticking in whole minutes 230 * using best available system clock. 231 * <p> 232 * This clock will always have the nano-of-second and second-of-minute fields set to zero. 233 * This ensures that the visible time ticks in whole minutes. 234 * The underlying clock is the best available system clock, equivalent to 235 * using {@link #system(ZoneId)}. 236 * <p> 237 * Implementations may use a caching strategy for performance reasons. 238 * As such, it is possible that the start of the minute observed via this 239 * clock will be later than that observed directly via the underlying clock. 240 * <p> 241 * The returned implementation is immutable, thread-safe and {@code Serializable}. 242 * It is equivalent to {@code tick(system(zone), Duration.ofMinutes(1))}. 243 * 244 * @param zone the time-zone to use to convert the instant to date-time, not null 245 * @return a clock that ticks in whole minutes using the specified zone, not null 246 */ 247 public static Clock tickMinutes(ZoneId zone) { 248 return new TickClock(system(zone), NANOS_PER_MINUTE); 249 } 250 251 /** 252 * Obtains a clock that returns instants from the specified clock truncated 253 * to the nearest occurrence of the specified duration. 254 * <p> 255 * This clock will only tick as per the specified duration. Thus, if the duration 256 * is half a second, the clock will return instants truncated to the half second. 257 * <p> 258 * The tick duration must be positive. If it has a part smaller than a whole 259 * millisecond, then the whole duration must divide into one second without 260 * leaving a remainder. All normal tick durations will match these criteria, 261 * including any multiple of hours, minutes, seconds and milliseconds, and 262 * sensible nanosecond durations, such as 20ns, 250,000ns and 500,000ns. 263 * <p> 264 * A duration of zero or one nanosecond would have no truncation effect. 265 * Passing one of these will return the underlying clock. 266 * <p> 267 * Implementations may use a caching strategy for performance reasons. 268 * As such, it is possible that the start of the requested duration observed 269 * via this clock will be later than that observed directly via the underlying clock. 270 * <p> 271 * The returned implementation is immutable, thread-safe and {@code Serializable} 272 * providing that the base clock is. 273 * 274 * @param baseClock the base clock to base the ticking clock on, not null 275 * @param tickDuration the duration of each visible tick, not negative, not null 276 * @return a clock that ticks in whole units of the duration, not null 277 * @throws IllegalArgumentException if the duration is negative, or has a 278 * part smaller than a whole millisecond such that the whole duration is not 279 * divisible into one second 280 * @throws ArithmeticException if the duration is too large to be represented as nanos 281 */ 282 public static Clock tick(Clock baseClock, Duration tickDuration) { 283 Objects.requireNonNull(baseClock, "baseClock"); 284 Objects.requireNonNull(tickDuration, "tickDuration"); 285 if (tickDuration.isNegative()) { 286 throw new IllegalArgumentException("Tick duration must not be negative"); 287 } 288 long tickNanos = tickDuration.toNanos(); 289 if (tickNanos % 1000_000 == 0) { 290 // ok, no fraction of millisecond 291 } else if (1000_000_000 % tickNanos == 0) { 292 // ok, divides into one second without remainder 293 } else { 294 throw new IllegalArgumentException("Invalid tick duration"); 295 } 296 if (tickNanos <= 1) { 297 return baseClock; 298 } 299 return new TickClock(baseClock, tickNanos); 300 } 301 302 //----------------------------------------------------------------------- 303 /** 304 * Obtains a clock that always returns the same instant. 305 * <p> 306 * This clock simply returns the specified instant. 307 * As such, it is not a clock in the conventional sense. 308 * The main use case for this is in testing, where the fixed clock ensures 309 * tests are not dependent on the current clock. 310 * <p> 311 * The returned implementation is immutable, thread-safe and {@code Serializable}. 312 * 313 * @param fixedInstant the instant to use as the clock, not null 314 * @param zone the time-zone to use to convert the instant to date-time, not null 315 * @return a clock that always returns the same instant, not null 316 */ 317 public static Clock fixed(Instant fixedInstant, ZoneId zone) { 318 Objects.requireNonNull(fixedInstant, "fixedInstant"); 319 Objects.requireNonNull(zone, "zone"); 320 return new FixedClock(fixedInstant, zone); 321 } 322 323 //------------------------------------------------------------------------- 324 /** 325 * Obtains a clock that returns instants from the specified clock with the 326 * specified duration added 327 * <p> 328 * This clock wraps another clock, returning instants that are later by the 329 * specified duration. If the duration is negative, the instants will be 330 * earlier than the current date and time. 331 * The main use case for this is to simulate running in the future or in the past. 332 * <p> 333 * A duration of zero would have no offsetting effect. 334 * Passing zero will return the underlying clock. 335 * <p> 336 * The returned implementation is immutable, thread-safe and {@code Serializable} 337 * providing that the base clock is. 338 * 339 * @param baseClock the base clock to add the duration to, not null 340 * @param offsetDuration the duration to add, not null 341 * @return a clock based on the base clock with the duration added, not null 342 */ 343 public static Clock offset(Clock baseClock, Duration offsetDuration) { 344 Objects.requireNonNull(baseClock, "baseClock"); 345 Objects.requireNonNull(offsetDuration, "offsetDuration"); 346 if (offsetDuration.equals(Duration.ZERO)) { 347 return baseClock; 348 } 349 return new OffsetClock(baseClock, offsetDuration); 350 } 351 352 //----------------------------------------------------------------------- 353 /** 354 * Constructor accessible by subclasses. 355 */ 356 protected Clock() { 357 } 358 359 //----------------------------------------------------------------------- 360 /** 361 * Gets the time-zone being used to create dates and times. 362 * <p> 363 * A clock will typically obtain the current instant and then convert that 364 * to a date or time using a time-zone. This method returns the time-zone used. 365 * 366 * @return the time-zone being used to interpret instants, not null 367 */ 368 public abstract ZoneId getZone(); 369 370 /** 371 * Returns a copy of this clock with a different time-zone. 372 * <p> 373 * A clock will typically obtain the current instant and then convert that 374 * to a date or time using a time-zone. This method returns a clock with 375 * similar properties but using a different time-zone. 376 * 377 * @param zone the time-zone to change to, not null 378 * @return a clock based on this clock with the specified time-zone, not null 379 */ 380 public abstract Clock withZone(ZoneId zone); 381 382 //------------------------------------------------------------------------- 383 /** 384 * Gets the current millisecond instant of the clock. 385 * <p> 386 * This returns the millisecond-based instant, measured from 1970-01-01T00:00Z (UTC). 387 * This is equivalent to the definition of {@link System#currentTimeMillis()}. 388 * <p> 389 * Most applications should avoid this method and use {@link Instant} to represent 390 * an instant on the time-line rather than a raw millisecond value. 391 * This method is provided to allow the use of the clock in high performance use cases 392 * where the creation of an object would be unacceptable. 393 * <p> 394 * The default implementation currently calls {@link #instant}. 395 * 396 * @return the current millisecond instant from this clock, measured from 397 * the Java epoch of 1970-01-01T00:00Z (UTC), not null 398 * @throws DateTimeException if the instant cannot be obtained, not thrown by most implementations 399 */ 400 public long millis() { 401 return instant().toEpochMilli(); 402 } 403 404 //----------------------------------------------------------------------- 405 /** 406 * Gets the current instant of the clock. 407 * <p> 408 * This returns an instant representing the current instant as defined by the clock. 409 * 410 * @return the current instant from this clock, not null 411 * @throws DateTimeException if the instant cannot be obtained, not thrown by most implementations 412 */ 413 public abstract Instant instant(); 414 415 //----------------------------------------------------------------------- 416 /** 417 * Checks if this clock is equal to another clock. 418 * <p> 419 * Clocks should override this method to compare equals based on 420 * their state and to meet the contract of {@link Object#equals}. 421 * If not overridden, the behavior is defined by {@link Object#equals} 422 * 423 * @param obj the object to check, null returns false 424 * @return true if this is equal to the other clock 425 */ 426 @Override 427 public boolean equals(Object obj) { 428 return super.equals(obj); 429 } 430 431 /** 432 * A hash code for this clock. 433 * <p> 434 * Clocks should override this method based on 435 * their state and to meet the contract of {@link Object#hashCode}. 436 * If not overridden, the behavior is defined by {@link Object#hashCode} 437 * 438 * @return a suitable hash code 439 */ 440 @Override 441 public int hashCode() { 442 return super.hashCode(); 443 } 444 445 //----------------------------------------------------------------------- 446 /** 447 * Implementation of a clock that always returns the latest time from 448 * {@link System#currentTimeMillis()}. 449 */ 450 static final class SystemClock extends Clock implements Serializable { 451 private static final long serialVersionUID = 6740630888130243051L; 452 private static final long OFFSET_SEED = 453 System.currentTimeMillis()/1000 - 1024; // initial offest 454 private final ZoneId zone; 455 // We don't actually need a volatile here. 456 // We don't care if offset is set or read concurrently by multiple 457 // threads - we just need a value which is 'recent enough' - in other 458 // words something that has been updated at least once in the last 459 // 2^32 secs (~136 years). And even if we by chance see an invalid 460 // offset, the worst that can happen is that we will get a -1 value 461 // from getNanoTimeAdjustment, forcing us to update the offset 462 // once again. 463 private transient long offset; 464 465 SystemClock(ZoneId zone) { 466 this.zone = zone; 467 this.offset = OFFSET_SEED; 468 } 469 @Override 470 public ZoneId getZone() { 471 return zone; 472 } 473 @Override 474 public Clock withZone(ZoneId zone) { 475 if (zone.equals(this.zone)) { // intentional NPE 476 return this; 477 } 478 return new SystemClock(zone); 479 } 480 @Override 481 public long millis() { 482 // System.currentTimeMillis() and VM.getNanoTimeAdjustment(offset) 483 // use the same time source - System.currentTimeMillis() simply 484 // limits the resolution to milliseconds. 485 // So we take the faster path and call System.currentTimeMillis() 486 // directly - in order to avoid the performance penalty of 487 // VM.getNanoTimeAdjustment(offset) which is less efficient. 488 return System.currentTimeMillis(); 489 } 490 @Override 491 public Instant instant() { 492 // Take a local copy of offset. offset can be updated concurrently 493 // by other threads (even if we haven't made it volatile) so we will 494 // work with a local copy. 495 long localOffset = offset; 496 long adjustment = VM.getNanoTimeAdjustment(localOffset); 497 498 if (adjustment == -1) { 499 // -1 is a sentinel value returned by VM.getNanoTimeAdjustment 500 // when the offset it is given is too far off the current UTC 501 // time. In principle, this should not happen unless the 502 // JVM has run for more than ~136 years (not likely) or 503 // someone is fiddling with the system time, or the offset is 504 // by chance at 1ns in the future (very unlikely). 505 // We can easily recover from all these conditions by bringing 506 // back the offset in range and retry. 507 508 // bring back the offset in range. We use -1024 to make 509 // it more unlikely to hit the 1ns in the future condition. 510 localOffset = System.currentTimeMillis()/1000 - 1024; 511 512 // retry 513 adjustment = VM.getNanoTimeAdjustment(localOffset); 514 515 if (adjustment == -1) { 516 // Should not happen: we just recomputed a new offset. 517 // It should have fixed the issue. 518 throw new InternalError("Offset " + localOffset + " is not in range"); 519 } else { 520 // OK - recovery succeeded. Update the offset for the 521 // next call... 522 offset = localOffset; 523 } 524 } 525 return Instant.ofEpochSecond(localOffset, adjustment); 526 } 527 @Override 528 public boolean equals(Object obj) { 529 if (obj instanceof SystemClock) { 530 return zone.equals(((SystemClock) obj).zone); 531 } 532 return false; 533 } 534 @Override 535 public int hashCode() { 536 return zone.hashCode() + 1; 537 } 538 @Override 539 public String toString() { 540 return "SystemClock[" + zone + "]"; 541 } 542 private void readObject(ObjectInputStream is) 543 throws IOException, ClassNotFoundException { 544 // ensure that offset is initialized 545 is.defaultReadObject(); 546 offset = OFFSET_SEED; 547 } 548 } 549 550 //----------------------------------------------------------------------- 551 /** 552 * Implementation of a clock that always returns the same instant. 553 * This is typically used for testing. 554 */ 555 static final class FixedClock extends Clock implements Serializable { 556 private static final long serialVersionUID = 7430389292664866958L; 557 private final Instant instant; 558 private final ZoneId zone; 559 560 FixedClock(Instant fixedInstant, ZoneId zone) { 561 this.instant = fixedInstant; 562 this.zone = zone; 563 } 564 @Override 565 public ZoneId getZone() { 566 return zone; 567 } 568 @Override 569 public Clock withZone(ZoneId zone) { 570 if (zone.equals(this.zone)) { // intentional NPE 571 return this; 572 } 573 return new FixedClock(instant, zone); 574 } 575 @Override 576 public long millis() { 577 return instant.toEpochMilli(); 578 } 579 @Override 580 public Instant instant() { 581 return instant; 582 } 583 @Override 584 public boolean equals(Object obj) { 585 if (obj instanceof FixedClock) { 586 FixedClock other = (FixedClock) obj; 587 return instant.equals(other.instant) && zone.equals(other.zone); 588 } 589 return false; 590 } 591 @Override 592 public int hashCode() { 593 return instant.hashCode() ^ zone.hashCode(); 594 } 595 @Override 596 public String toString() { 597 return "FixedClock[" + instant + "," + zone + "]"; 598 } 599 } 600 601 //----------------------------------------------------------------------- 602 /** 603 * Implementation of a clock that adds an offset to an underlying clock. 604 */ 605 static final class OffsetClock extends Clock implements Serializable { 606 private static final long serialVersionUID = 2007484719125426256L; 607 private final Clock baseClock; 608 private final Duration offset; 609 610 OffsetClock(Clock baseClock, Duration offset) { 611 this.baseClock = baseClock; 612 this.offset = offset; 613 } 614 @Override 615 public ZoneId getZone() { 616 return baseClock.getZone(); 617 } 618 @Override 619 public Clock withZone(ZoneId zone) { 620 if (zone.equals(baseClock.getZone())) { // intentional NPE 621 return this; 622 } 623 return new OffsetClock(baseClock.withZone(zone), offset); 624 } 625 @Override 626 public long millis() { 627 return Math.addExact(baseClock.millis(), offset.toMillis()); 628 } 629 @Override 630 public Instant instant() { 631 return baseClock.instant().plus(offset); 632 } 633 @Override 634 public boolean equals(Object obj) { 635 if (obj instanceof OffsetClock) { 636 OffsetClock other = (OffsetClock) obj; 637 return baseClock.equals(other.baseClock) && offset.equals(other.offset); 638 } 639 return false; 640 } 641 @Override 642 public int hashCode() { 643 return baseClock.hashCode() ^ offset.hashCode(); 644 } 645 @Override 646 public String toString() { 647 return "OffsetClock[" + baseClock + "," + offset + "]"; 648 } 649 } 650 651 //----------------------------------------------------------------------- 652 /** 653 * Implementation of a clock that adds an offset to an underlying clock. 654 */ 655 static final class TickClock extends Clock implements Serializable { 656 private static final long serialVersionUID = 6504659149906368850L; 657 private final Clock baseClock; 658 private final long tickNanos; 659 660 TickClock(Clock baseClock, long tickNanos) { 661 this.baseClock = baseClock; 662 this.tickNanos = tickNanos; 663 } 664 @Override 665 public ZoneId getZone() { 666 return baseClock.getZone(); 667 } 668 @Override 669 public Clock withZone(ZoneId zone) { 670 if (zone.equals(baseClock.getZone())) { // intentional NPE 671 return this; 672 } 673 return new TickClock(baseClock.withZone(zone), tickNanos); 674 } 675 @Override 676 public long millis() { 677 long millis = baseClock.millis(); 678 return millis - Math.floorMod(millis, tickNanos / 1000_000L); 679 } 680 @Override 681 public Instant instant() { 682 if ((tickNanos % 1000_000) == 0) { 683 long millis = baseClock.millis(); 684 return Instant.ofEpochMilli(millis - Math.floorMod(millis, tickNanos / 1000_000L)); 685 } 686 Instant instant = baseClock.instant(); 687 long nanos = instant.getNano(); 688 long adjust = Math.floorMod(nanos, tickNanos); 689 return instant.minusNanos(adjust); 690 } 691 @Override 692 public boolean equals(Object obj) { 693 if (obj instanceof TickClock) { 694 TickClock other = (TickClock) obj; 695 return baseClock.equals(other.baseClock) && tickNanos == other.tickNanos; 696 } 697 return false; 698 } 699 @Override 700 public int hashCode() { 701 return baseClock.hashCode() ^ ((int) (tickNanos ^ (tickNanos >>> 32))); 702 } 703 @Override 704 public String toString() { 705 return "TickClock[" + baseClock + "," + Duration.ofNanos(tickNanos) + "]"; 706 } 707 } 708 709 }