Summary
Add java.time.Instant method plusSaturating(Duration).
Problem
To implement a timeout specified by a duration, one might convert that duration into a deadline instant and then track the current time instant, rather than tracking the elapsed duration. A deadline is an instant obtained by adding a duration to a reference instant; for example, Instant.now().plus(duration). However, this addition can overflow or fall outside the valid Instant range, which may be undesirable.
Solution
Provide a method to add a Duration to an Instant using saturating arithmetic. That is, a method that never overflows or exceeds the Instant range, and returns the nearest bound (Instant.MIN or Instant.MAX) instead of throwing an exception.
Specification
diff --git a/src/java.base/share/classes/java/time/Instant.java b/src/java.base/share/classes/java/time/Instant.java
index 1c7a41d7f0e..26e7e84228f 100644
--- a/src/java.base/share/classes/java/time/Instant.java
+++ b/src/java.base/share/classes/java/time/Instant.java
@@ -788,6 +788,32 @@ public Instant plus(TemporalAmount amountToAdd) {
return (Instant) amountToAdd.addTo(this);
}
+ /**
+ * Returns a copy of this instant with the specified duration added, with
+ * saturated semantics.
+ * <p>
+ * If the result is "earlier" than {@link Instant#MIN}, this method returns
+ * {@code MIN}. If the result is "later" than {@link Instant#MAX}, it
+ * returns {@code MAX}. Otherwise it returns {@link #plus(TemporalAmount) plus(duration)}.
+ *
+ * @apiNote This method can be used to calculate a deadline from
+ * this instant and a timeout. Unlike {@code plus(duration)},
+ * this method never throws {@link ArithmeticException} or {@link DateTimeException}
+ * due to numeric overflow or {@code Instant} range violation.
+ *
+ * @param duration the duration to add, not null
+ * @return an {@code Instant} based on this instant with the addition made, not null
+ *
+ * @since 26
+ */
+ public Instant plusSaturating(Duration duration) {
- csr of
-
JDK-8368856 Add a method that performs saturating addition of a Duration to an Instant
-
- Open
-