Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/jdk17u
Path: blob/master/src/java.base/share/classes/java/time/Clock.java
67862 views
1
/*
2
* Copyright (c) 2012, 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
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 java.io.ObjectStreamException;
67
68
import static java.time.LocalTime.NANOS_PER_MINUTE;
69
import static java.time.LocalTime.NANOS_PER_SECOND;
70
import static java.time.LocalTime.NANOS_PER_MILLI;
71
import java.io.Serializable;
72
import java.util.Objects;
73
import java.util.TimeZone;
74
import jdk.internal.misc.VM;
75
76
/**
77
* A clock providing access to the current instant, date and time using a time-zone.
78
* <p>
79
* Instances of this abstract class are used to access a pluggable representation of the
80
* current instant, which can be interpreted using the stored time-zone to find the
81
* current date and time.
82
* For example, {@code Clock} can be used instead of {@link System#currentTimeMillis()}
83
* and {@link TimeZone#getDefault()}.
84
* <p>
85
* Use of a {@code Clock} is optional. All key date-time classes also have a
86
* {@code now()} factory method that uses the system clock in the default time zone.
87
* The primary purpose of this abstraction is to allow alternate clocks to be
88
* plugged in as and when required. Applications use an object to obtain the
89
* current time rather than a static method. This can simplify testing.
90
* <p>
91
* As such, this abstract class does not guarantee the result actually represents the current instant
92
* on the time-line. Instead, it allows the application to provide a controlled view as to what
93
* the current instant and time-zone are.
94
* <p>
95
* Best practice for applications is to pass a {@code Clock} into any method
96
* that requires the current instant and time-zone. A dependency injection framework
97
* is one way to achieve this:
98
* <pre>
99
* public class MyBean {
100
* private Clock clock; // dependency inject
101
* ...
102
* public void process(LocalDate eventDate) {
103
* if (eventDate.isBefore(LocalDate.now(clock)) {
104
* ...
105
* }
106
* }
107
* }
108
* </pre>
109
* This approach allows an alternative clock, such as {@link #fixed(Instant, ZoneId) fixed}
110
* or {@link #offset(Clock, Duration) offset} to be used during testing.
111
* <p>
112
* The {@code system} factory methods provide clocks based on the best available
113
* system clock. This may use {@link System#currentTimeMillis()}, or a higher
114
* resolution clock if one is available.
115
*
116
* @implSpec
117
* This abstract class must be implemented with care to ensure other classes operate correctly.
118
* All implementations must be thread-safe - a single instance must be capable of be invoked
119
* from multiple threads without negative consequences such as race conditions.
120
* <p>
121
* The principal methods are defined to allow the throwing of an exception.
122
* In normal use, no exceptions will be thrown, however one possible implementation would be to
123
* obtain the time from a central time server across the network. Obviously, in this case the
124
* lookup could fail, and so the method is permitted to throw an exception.
125
* <p>
126
* The returned instants from {@code Clock} work on a time-scale that ignores leap seconds,
127
* as described in {@link Instant}. If the implementation wraps a source that provides leap
128
* second information, then a mechanism should be used to "smooth" the leap second.
129
* The Java Time-Scale mandates the use of UTC-SLS, however clock implementations may choose
130
* how accurate they are with the time-scale so long as they document how they work.
131
* Implementations are therefore not required to actually perform the UTC-SLS slew or to
132
* otherwise be aware of leap seconds.
133
* <p>
134
* Implementations should implement {@code Serializable} wherever possible and must
135
* document whether or not they do support serialization.
136
*
137
* @see InstantSource
138
*
139
* @since 1.8
140
*/
141
public abstract class Clock implements InstantSource {
142
143
/**
144
* Obtains a clock that returns the current instant using the best available
145
* system clock, converting to date and time using the UTC time-zone.
146
* <p>
147
* This clock, rather than {@link #systemDefaultZone()}, should be used when
148
* you need the current instant without the date or time.
149
* <p>
150
* This clock is based on the best available system clock.
151
* This may use {@link System#currentTimeMillis()}, or a higher resolution
152
* clock if one is available.
153
* <p>
154
* Conversion from instant to date or time uses the {@linkplain ZoneOffset#UTC UTC time-zone}.
155
* <p>
156
* The returned implementation is immutable, thread-safe and {@code Serializable}.
157
* It is equivalent to {@code system(ZoneOffset.UTC)}.
158
*
159
* @return a clock that uses the best available system clock in the UTC zone, not null
160
*/
161
public static Clock systemUTC() {
162
return SystemClock.UTC;
163
}
164
165
/**
166
* Obtains a clock that returns the current instant using the best available
167
* system clock, converting to date and time using the default time-zone.
168
* <p>
169
* This clock is based on the best available system clock.
170
* This may use {@link System#currentTimeMillis()}, or a higher resolution
171
* clock if one is available.
172
* <p>
173
* Using this method hard codes a dependency to the default time-zone into your application.
174
* It is recommended to avoid this and use a specific time-zone whenever possible.
175
* The {@link #systemUTC() UTC clock} should be used when you need the current instant
176
* without the date or time.
177
* <p>
178
* The returned implementation is immutable, thread-safe and {@code Serializable}.
179
* It is equivalent to {@code system(ZoneId.systemDefault())}.
180
*
181
* @return a clock that uses the best available system clock in the default zone, not null
182
* @see ZoneId#systemDefault()
183
*/
184
public static Clock systemDefaultZone() {
185
return new SystemClock(ZoneId.systemDefault());
186
}
187
188
/**
189
* Obtains a clock that returns the current instant using the best available
190
* system clock.
191
* <p>
192
* This clock is based on the best available system clock.
193
* This may use {@link System#currentTimeMillis()}, or a higher resolution
194
* clock if one is available.
195
* <p>
196
* Conversion from instant to date or time uses the specified time-zone.
197
* <p>
198
* The returned implementation is immutable, thread-safe and {@code Serializable}.
199
*
200
* @param zone the time-zone to use to convert the instant to date-time, not null
201
* @return a clock that uses the best available system clock in the specified zone, not null
202
*/
203
public static Clock system(ZoneId zone) {
204
Objects.requireNonNull(zone, "zone");
205
if (zone == ZoneOffset.UTC) {
206
return SystemClock.UTC;
207
}
208
return new SystemClock(zone);
209
}
210
211
//-------------------------------------------------------------------------
212
/**
213
* Obtains a clock that returns the current instant ticking in whole milliseconds
214
* using the best available system clock.
215
* <p>
216
* This clock will always have the nano-of-second field truncated to milliseconds.
217
* This ensures that the visible time ticks in whole milliseconds.
218
* The underlying clock is the best available system clock, equivalent to
219
* using {@link #system(ZoneId)}.
220
* <p>
221
* Implementations may use a caching strategy for performance reasons.
222
* As such, it is possible that the start of the millisecond observed via this
223
* clock will be later than that observed directly via the underlying clock.
224
* <p>
225
* The returned implementation is immutable, thread-safe and {@code Serializable}.
226
* It is equivalent to {@code tick(system(zone), Duration.ofMillis(1))}.
227
*
228
* @param zone the time-zone to use to convert the instant to date-time, not null
229
* @return a clock that ticks in whole milliseconds using the specified zone, not null
230
* @since 9
231
*/
232
public static Clock tickMillis(ZoneId zone) {
233
return new TickClock(system(zone), NANOS_PER_MILLI);
234
}
235
236
//-------------------------------------------------------------------------
237
/**
238
* Obtains a clock that returns the current instant ticking in whole seconds
239
* using the best available system clock.
240
* <p>
241
* This clock will always have the nano-of-second field set to zero.
242
* This ensures that the visible time ticks in whole seconds.
243
* The underlying clock is the best available system clock, equivalent to
244
* using {@link #system(ZoneId)}.
245
* <p>
246
* Implementations may use a caching strategy for performance reasons.
247
* As such, it is possible that the start of the second observed via this
248
* clock will be later than that observed directly via the underlying clock.
249
* <p>
250
* The returned implementation is immutable, thread-safe and {@code Serializable}.
251
* It is equivalent to {@code tick(system(zone), Duration.ofSeconds(1))}.
252
*
253
* @param zone the time-zone to use to convert the instant to date-time, not null
254
* @return a clock that ticks in whole seconds using the specified zone, not null
255
*/
256
public static Clock tickSeconds(ZoneId zone) {
257
return new TickClock(system(zone), NANOS_PER_SECOND);
258
}
259
260
/**
261
* Obtains a clock that returns the current instant ticking in whole minutes
262
* using the best available system clock.
263
* <p>
264
* This clock will always have the nano-of-second and second-of-minute fields set to zero.
265
* This ensures that the visible time ticks in whole minutes.
266
* The underlying clock is the best available system clock, equivalent to
267
* using {@link #system(ZoneId)}.
268
* <p>
269
* Implementations may use a caching strategy for performance reasons.
270
* As such, it is possible that the start of the minute observed via this
271
* clock will be later than that observed directly via the underlying clock.
272
* <p>
273
* The returned implementation is immutable, thread-safe and {@code Serializable}.
274
* It is equivalent to {@code tick(system(zone), Duration.ofMinutes(1))}.
275
*
276
* @param zone the time-zone to use to convert the instant to date-time, not null
277
* @return a clock that ticks in whole minutes using the specified zone, not null
278
*/
279
public static Clock tickMinutes(ZoneId zone) {
280
return new TickClock(system(zone), NANOS_PER_MINUTE);
281
}
282
283
/**
284
* Obtains a clock that returns instants from the specified clock truncated
285
* to the nearest occurrence of the specified duration.
286
* <p>
287
* This clock will only tick as per the specified duration. Thus, if the duration
288
* is half a second, the clock will return instants truncated to the half second.
289
* <p>
290
* The tick duration must be positive. If it has a part smaller than a whole
291
* millisecond, then the whole duration must divide into one second without
292
* leaving a remainder. All normal tick durations will match these criteria,
293
* including any multiple of hours, minutes, seconds and milliseconds, and
294
* sensible nanosecond durations, such as 20ns, 250,000ns and 500,000ns.
295
* <p>
296
* A duration of zero or one nanosecond would have no truncation effect.
297
* Passing one of these will return the underlying clock.
298
* <p>
299
* Implementations may use a caching strategy for performance reasons.
300
* As such, it is possible that the start of the requested duration observed
301
* via this clock will be later than that observed directly via the underlying clock.
302
* <p>
303
* The returned implementation is immutable, thread-safe and {@code Serializable}
304
* providing that the base clock is.
305
*
306
* @param baseClock the base clock to base the ticking clock on, not null
307
* @param tickDuration the duration of each visible tick, not negative, not null
308
* @return a clock that ticks in whole units of the duration, not null
309
* @throws IllegalArgumentException if the duration is negative, or has a
310
* part smaller than a whole millisecond such that the whole duration is not
311
* divisible into one second
312
* @throws ArithmeticException if the duration is too large to be represented as nanos
313
*/
314
public static Clock tick(Clock baseClock, Duration tickDuration) {
315
Objects.requireNonNull(baseClock, "baseClock");
316
Objects.requireNonNull(tickDuration, "tickDuration");
317
if (tickDuration.isNegative()) {
318
throw new IllegalArgumentException("Tick duration must not be negative");
319
}
320
long tickNanos = tickDuration.toNanos();
321
if (tickNanos % 1000_000 == 0) {
322
// ok, no fraction of millisecond
323
} else if (1000_000_000 % tickNanos == 0) {
324
// ok, divides into one second without remainder
325
} else {
326
throw new IllegalArgumentException("Invalid tick duration");
327
}
328
if (tickNanos <= 1) {
329
return baseClock;
330
}
331
return new TickClock(baseClock, tickNanos);
332
}
333
334
//-----------------------------------------------------------------------
335
/**
336
* Obtains a clock that always returns the same instant.
337
* <p>
338
* This clock simply returns the specified instant.
339
* As such, it is not a clock in the conventional sense.
340
* The main use case for this is in testing, where the fixed clock ensures
341
* tests are not dependent on the current clock.
342
* <p>
343
* The returned implementation is immutable, thread-safe and {@code Serializable}.
344
*
345
* @param fixedInstant the instant to use as the clock, not null
346
* @param zone the time-zone to use to convert the instant to date-time, not null
347
* @return a clock that always returns the same instant, not null
348
*/
349
public static Clock fixed(Instant fixedInstant, ZoneId zone) {
350
Objects.requireNonNull(fixedInstant, "fixedInstant");
351
Objects.requireNonNull(zone, "zone");
352
return new FixedClock(fixedInstant, zone);
353
}
354
355
//-------------------------------------------------------------------------
356
/**
357
* Obtains a clock that returns instants from the specified clock with the
358
* specified duration added.
359
* <p>
360
* This clock wraps another clock, returning instants that are later by the
361
* specified duration. If the duration is negative, the instants will be
362
* earlier than the current date and time.
363
* The main use case for this is to simulate running in the future or in the past.
364
* <p>
365
* A duration of zero would have no offsetting effect.
366
* Passing zero will return the underlying clock.
367
* <p>
368
* The returned implementation is immutable, thread-safe and {@code Serializable}
369
* providing that the base clock is.
370
*
371
* @param baseClock the base clock to add the duration to, not null
372
* @param offsetDuration the duration to add, not null
373
* @return a clock based on the base clock with the duration added, not null
374
*/
375
public static Clock offset(Clock baseClock, Duration offsetDuration) {
376
Objects.requireNonNull(baseClock, "baseClock");
377
Objects.requireNonNull(offsetDuration, "offsetDuration");
378
if (offsetDuration.equals(Duration.ZERO)) {
379
return baseClock;
380
}
381
return new OffsetClock(baseClock, offsetDuration);
382
}
383
384
//-----------------------------------------------------------------------
385
/**
386
* Constructor accessible by subclasses.
387
*/
388
protected Clock() {
389
}
390
391
//-----------------------------------------------------------------------
392
/**
393
* Gets the time-zone being used to create dates and times.
394
* <p>
395
* A clock will typically obtain the current instant and then convert that
396
* to a date or time using a time-zone. This method returns the time-zone used.
397
*
398
* @return the time-zone being used to interpret instants, not null
399
*/
400
public abstract ZoneId getZone();
401
402
/**
403
* Returns a copy of this clock with a different time-zone.
404
* <p>
405
* A clock will typically obtain the current instant and then convert that
406
* to a date or time using a time-zone. This method returns a clock with
407
* similar properties but using a different time-zone.
408
*
409
* @param zone the time-zone to change to, not null
410
* @return a clock based on this clock with the specified time-zone, not null
411
*/
412
@Override
413
public abstract Clock withZone(ZoneId zone);
414
415
//-------------------------------------------------------------------------
416
/**
417
* Gets the current millisecond instant of the clock.
418
* <p>
419
* This returns the millisecond-based instant, measured from 1970-01-01T00:00Z (UTC).
420
* This is equivalent to the definition of {@link System#currentTimeMillis()}.
421
* <p>
422
* Most applications should avoid this method and use {@link Instant} to represent
423
* an instant on the time-line rather than a raw millisecond value.
424
* This method is provided to allow the use of the clock in high performance use cases
425
* where the creation of an object would be unacceptable.
426
* <p>
427
* The default implementation currently calls {@link #instant}.
428
*
429
* @return the current millisecond instant from this clock, measured from
430
* the Java epoch of 1970-01-01T00:00Z (UTC), not null
431
* @throws DateTimeException if the instant cannot be obtained, not thrown by most implementations
432
*/
433
@Override
434
public long millis() {
435
return instant().toEpochMilli();
436
}
437
438
//-----------------------------------------------------------------------
439
/**
440
* Gets the current instant of the clock.
441
* <p>
442
* This returns an instant representing the current instant as defined by the clock.
443
*
444
* @return the current instant from this clock, not null
445
* @throws DateTimeException if the instant cannot be obtained, not thrown by most implementations
446
*/
447
@Override
448
public abstract Instant instant();
449
450
//-----------------------------------------------------------------------
451
/**
452
* Checks if this clock is equal to another clock.
453
* <p>
454
* Clocks should override this method to compare equals based on
455
* their state and to meet the contract of {@link Object#equals}.
456
* If not overridden, the behavior is defined by {@link Object#equals}
457
*
458
* @param obj the object to check, null returns false
459
* @return true if this is equal to the other clock
460
*/
461
@Override
462
public boolean equals(Object obj) {
463
return super.equals(obj);
464
}
465
466
/**
467
* A hash code for this clock.
468
* <p>
469
* Clocks should override this method based on
470
* their state and to meet the contract of {@link Object#hashCode}.
471
* If not overridden, the behavior is defined by {@link Object#hashCode}
472
*
473
* @return a suitable hash code
474
*/
475
@Override
476
public int hashCode() {
477
return super.hashCode();
478
}
479
480
//-----------------------------------------------------------------------
481
// initial offset
482
private static final long OFFSET_SEED = System.currentTimeMillis() / 1000 - 1024;
483
// We don't actually need a volatile here.
484
// We don't care if offset is set or read concurrently by multiple
485
// threads - we just need a value which is 'recent enough' - in other
486
// words something that has been updated at least once in the last
487
// 2^32 secs (~136 years). And even if we by chance see an invalid
488
// offset, the worst that can happen is that we will get a -1 value
489
// from getNanoTimeAdjustment, forcing us to update the offset
490
// once again.
491
private static long offset = OFFSET_SEED;
492
493
static Instant currentInstant() {
494
// Take a local copy of offset. offset can be updated concurrently
495
// by other threads (even if we haven't made it volatile) so we will
496
// work with a local copy.
497
long localOffset = offset;
498
long adjustment = VM.getNanoTimeAdjustment(localOffset);
499
500
if (adjustment == -1) {
501
// -1 is a sentinel value returned by VM.getNanoTimeAdjustment
502
// when the offset it is given is too far off the current UTC
503
// time. In principle, this should not happen unless the
504
// JVM has run for more than ~136 years (not likely) or
505
// someone is fiddling with the system time, or the offset is
506
// by chance at 1ns in the future (very unlikely).
507
// We can easily recover from all these conditions by bringing
508
// back the offset in range and retry.
509
510
// bring back the offset in range. We use -1024 to make
511
// it more unlikely to hit the 1ns in the future condition.
512
localOffset = System.currentTimeMillis() / 1000 - 1024;
513
514
// retry
515
adjustment = VM.getNanoTimeAdjustment(localOffset);
516
517
if (adjustment == -1) {
518
// Should not happen: we just recomputed a new offset.
519
// It should have fixed the issue.
520
throw new InternalError("Offset " + localOffset + " is not in range");
521
} else {
522
// OK - recovery succeeded. Update the offset for the
523
// next call...
524
offset = localOffset;
525
}
526
}
527
return Instant.ofEpochSecond(localOffset, adjustment);
528
}
529
530
//-----------------------------------------------------------------------
531
/**
532
* An instant source that always returns the latest time from
533
* {@link System#currentTimeMillis()} or equivalent.
534
*/
535
static final class SystemInstantSource implements InstantSource, Serializable {
536
@java.io.Serial
537
private static final long serialVersionUID = 3232399674412L;
538
// this is a singleton, but the class is coded such that it is not a
539
// problem if someone hacks around and creates another instance
540
static final SystemInstantSource INSTANCE = new SystemInstantSource();
541
542
SystemInstantSource() {
543
}
544
@Override
545
public Clock withZone(ZoneId zone) {
546
return Clock.system(zone);
547
}
548
@Override
549
public long millis() {
550
// System.currentTimeMillis() and VM.getNanoTimeAdjustment(offset)
551
// use the same time source - System.currentTimeMillis() simply
552
// limits the resolution to milliseconds.
553
// So we take the faster path and call System.currentTimeMillis()
554
// directly - in order to avoid the performance penalty of
555
// VM.getNanoTimeAdjustment(offset) which is less efficient.
556
return System.currentTimeMillis();
557
}
558
@Override
559
public Instant instant() {
560
return currentInstant();
561
}
562
@Override
563
public boolean equals(Object obj) {
564
return obj instanceof SystemInstantSource;
565
}
566
@Override
567
public int hashCode() {
568
return SystemInstantSource.class.hashCode();
569
}
570
@Override
571
public String toString() {
572
return "SystemInstantSource";
573
}
574
@java.io.Serial
575
private Object readResolve() throws ObjectStreamException {
576
return SystemInstantSource.INSTANCE;
577
}
578
}
579
580
//-----------------------------------------------------------------------
581
/**
582
* Implementation of a clock that always returns the latest time from
583
* {@code SystemInstantSource.INSTANCE}.
584
*/
585
static final class SystemClock extends Clock implements Serializable {
586
@java.io.Serial
587
private static final long serialVersionUID = 6740630888130243051L;
588
static final SystemClock UTC = new SystemClock(ZoneOffset.UTC);
589
590
private final ZoneId zone;
591
592
SystemClock(ZoneId zone) {
593
this.zone = zone;
594
}
595
@Override
596
public ZoneId getZone() {
597
return zone;
598
}
599
@Override
600
public Clock withZone(ZoneId zone) {
601
if (zone.equals(this.zone)) { // intentional NPE
602
return this;
603
}
604
return new SystemClock(zone);
605
}
606
@Override
607
public long millis() {
608
// inline of SystemInstantSource.INSTANCE.millis()
609
return System.currentTimeMillis();
610
}
611
@Override
612
public Instant instant() {
613
// inline of SystemInstantSource.INSTANCE.instant()
614
return currentInstant();
615
}
616
@Override
617
public boolean equals(Object obj) {
618
if (obj instanceof SystemClock) {
619
return zone.equals(((SystemClock) obj).zone);
620
}
621
return false;
622
}
623
@Override
624
public int hashCode() {
625
return zone.hashCode() + 1;
626
}
627
@Override
628
public String toString() {
629
return "SystemClock[" + zone + "]";
630
}
631
}
632
633
//-----------------------------------------------------------------------
634
/**
635
* Implementation of a clock that always returns the same instant.
636
* This is typically used for testing.
637
*/
638
static final class FixedClock extends Clock implements Serializable {
639
@java.io.Serial
640
private static final long serialVersionUID = 7430389292664866958L;
641
private final Instant instant;
642
private final ZoneId zone;
643
644
FixedClock(Instant fixedInstant, ZoneId zone) {
645
this.instant = fixedInstant;
646
this.zone = zone;
647
}
648
@Override
649
public ZoneId getZone() {
650
return zone;
651
}
652
@Override
653
public Clock withZone(ZoneId zone) {
654
if (zone.equals(this.zone)) { // intentional NPE
655
return this;
656
}
657
return new FixedClock(instant, zone);
658
}
659
@Override
660
public long millis() {
661
return instant.toEpochMilli();
662
}
663
@Override
664
public Instant instant() {
665
return instant;
666
}
667
@Override
668
public boolean equals(Object obj) {
669
return obj instanceof FixedClock other
670
&& instant.equals(other.instant)
671
&& zone.equals(other.zone);
672
}
673
@Override
674
public int hashCode() {
675
return instant.hashCode() ^ zone.hashCode();
676
}
677
@Override
678
public String toString() {
679
return "FixedClock[" + instant + "," + zone + "]";
680
}
681
}
682
683
//-----------------------------------------------------------------------
684
/**
685
* Implementation of a clock that adds an offset to an underlying clock.
686
*/
687
static final class OffsetClock extends Clock implements Serializable {
688
@java.io.Serial
689
private static final long serialVersionUID = 2007484719125426256L;
690
@SuppressWarnings("serial") // Not statically typed as Serializable
691
private final Clock baseClock;
692
private final Duration offset;
693
694
OffsetClock(Clock baseClock, Duration offset) {
695
this.baseClock = baseClock;
696
this.offset = offset;
697
}
698
@Override
699
public ZoneId getZone() {
700
return baseClock.getZone();
701
}
702
@Override
703
public Clock withZone(ZoneId zone) {
704
if (zone.equals(baseClock.getZone())) { // intentional NPE
705
return this;
706
}
707
return new OffsetClock(baseClock.withZone(zone), offset);
708
}
709
@Override
710
public long millis() {
711
return Math.addExact(baseClock.millis(), offset.toMillis());
712
}
713
@Override
714
public Instant instant() {
715
return baseClock.instant().plus(offset);
716
}
717
@Override
718
public boolean equals(Object obj) {
719
return obj instanceof OffsetClock other
720
&& baseClock.equals(other.baseClock)
721
&& offset.equals(other.offset);
722
}
723
@Override
724
public int hashCode() {
725
return baseClock.hashCode() ^ offset.hashCode();
726
}
727
@Override
728
public String toString() {
729
return "OffsetClock[" + baseClock + "," + offset + "]";
730
}
731
}
732
733
//-----------------------------------------------------------------------
734
/**
735
* Implementation of a clock that reduces the tick frequency of an underlying clock.
736
*/
737
static final class TickClock extends Clock implements Serializable {
738
@java.io.Serial
739
private static final long serialVersionUID = 6504659149906368850L;
740
@SuppressWarnings("serial") // Not statically typed as Serializable
741
private final Clock baseClock;
742
private final long tickNanos;
743
744
TickClock(Clock baseClock, long tickNanos) {
745
this.baseClock = baseClock;
746
this.tickNanos = tickNanos;
747
}
748
@Override
749
public ZoneId getZone() {
750
return baseClock.getZone();
751
}
752
@Override
753
public Clock withZone(ZoneId zone) {
754
if (zone.equals(baseClock.getZone())) { // intentional NPE
755
return this;
756
}
757
return new TickClock(baseClock.withZone(zone), tickNanos);
758
}
759
@Override
760
public long millis() {
761
long millis = baseClock.millis();
762
return millis - Math.floorMod(millis, tickNanos / 1000_000L);
763
}
764
@Override
765
public Instant instant() {
766
if ((tickNanos % 1000_000) == 0) {
767
long millis = baseClock.millis();
768
return Instant.ofEpochMilli(millis - Math.floorMod(millis, tickNanos / 1000_000L));
769
}
770
Instant instant = baseClock.instant();
771
long nanos = instant.getNano();
772
long adjust = Math.floorMod(nanos, tickNanos);
773
return instant.minusNanos(adjust);
774
}
775
@Override
776
public boolean equals(Object obj) {
777
return (obj instanceof TickClock other)
778
&& tickNanos == other.tickNanos
779
&& baseClock.equals(other.baseClock);
780
}
781
@Override
782
public int hashCode() {
783
return baseClock.hashCode() ^ ((int) (tickNanos ^ (tickNanos >>> 32)));
784
}
785
@Override
786
public String toString() {
787
return "TickClock[" + baseClock + "," + Duration.ofNanos(tickNanos) + "]";
788
}
789
}
790
791
//-----------------------------------------------------------------------
792
/**
793
* Implementation of a clock based on an {@code InstantSource}.
794
*/
795
static final class SourceClock extends Clock implements Serializable {
796
@java.io.Serial
797
private static final long serialVersionUID = 235386528762398L;
798
@SuppressWarnings("serial") // Not statically typed as Serializable
799
private final InstantSource baseSource;
800
private final ZoneId zone;
801
802
SourceClock(InstantSource baseSource, ZoneId zone) {
803
this.baseSource = baseSource;
804
this.zone = zone;
805
}
806
@Override
807
public ZoneId getZone() {
808
return zone;
809
}
810
@Override
811
public Clock withZone(ZoneId zone) {
812
if (zone.equals(this.zone)) { // intentional NPE
813
return this;
814
}
815
return new SourceClock(baseSource, zone);
816
}
817
@Override
818
public long millis() {
819
return baseSource.millis();
820
}
821
@Override
822
public Instant instant() {
823
return baseSource.instant();
824
}
825
@Override
826
public boolean equals(Object obj) {
827
return (obj instanceof SourceClock other)
828
&& zone.equals(other.zone)
829
&& baseSource.equals(other.baseSource);
830
}
831
@Override
832
public int hashCode() {
833
return baseSource.hashCode() ^ zone.hashCode();
834
}
835
@Override
836
public String toString() {
837
return "SourceClock[" + baseSource + "," + zone + "]";
838
}
839
}
840
841
}
842
843