RFR: 8368856: Add methods for saturating Duration arithmetic to Instant [v7]
Roger Riggs
rriggs at openjdk.org
Wed Oct 8 18:21:41 UTC 2025
On Wed, 1 Oct 2025 20:17:00 GMT, Pavel Rappo <prappo at openjdk.org> wrote:
>> We recently [discussed] the possibility of introducing saturating arithmetic for deadline computation. Consider this PR as a starting point. Once we agree on the implementation, I'll file a CSR.
>>
>> I created a method in `Instant` to add `Duration`. One could argue that the proper way would be to go all the way and create a method in `Temporal` to add `TemporalAmount`. Or maybe even expand the functionality, and create an additional method in `Temporal` to subtract `TemporalAmount`.
>>
>> My current thinking is that if we were to do that, there would be a lot of expensive, unused code. Saturating logic seems to be only useful for `Instant` and `Duration`.
>>
>> Even if we decide to extend `Temporal` to add/subtract `TemporalAmount`, it could always be done later. From the perspective of `Instant`, `plus(TemporalAmount)` will be just an overload of `plus(Duration)`.
>>
>> [discussed]: https://mail.openjdk.org/pipermail/core-libs-dev/2025-September/151098.html
>
> Pavel Rappo has updated the pull request incrementally with one additional commit since the last revision:
>
> Fix copy-paste typos
src/java.base/share/classes/java/time/Instant.java line 814:
> 812: ? this.plus(duration) : Instant.MAX;
> 813: }
> 814: }
Can this be generalized to work across Temporals? To allow expansion later.
Addi a default method to the Temporal interface for `plusSaturating(TemporalAmount amount)`.
The default method can throw Unsupported Exception.
The override in Instant can be implemented as above and throw UnsupportedTemporalType for all other temporalAmounts.
The javadoc can use Duration for the example.
This would allow more types to consistently support saturating arithmetic.
src/java.base/share/classes/java/time/Instant.java line 1011:
> 1009: }
> 1010: }
> 1011:
Omit minusSaturating, I think subtraction is much less common and even more so to exceed the negative range.
The caller can negate their argument and use plus if that's needed.
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/27549#discussion_r2414667478
PR Review Comment: https://git.openjdk.org/jdk/pull/27549#discussion_r2414671503
More information about the core-libs-dev
mailing list