RFR: 8318051: Duration.between uses exceptions for control flow

Eamonn McManus emcmanus at openjdk.org
Mon Oct 23 17:39:43 UTC 2023


The existing logic uses nanosecond arithmetic to compute Duration.between. Since that can overflow for durations greater than 292 years, it has a try/catch that falls back to computing the seconds part and adjusting that for nanoseconds. However, exception handling is typically very expensive, so in cases like the one in the linked bug this method was a performance trap.

The new logic is essentially the old catch block. It needs a special case for when the number of seconds is 0, so it is slightly slower in that case. But in other cases it is probably somewhat faster, because it avoids a
[division](https://github.com/openjdk/jdk/blob/8d9a4b43f4fff30fd217dab2c224e641cb913c18/src/java.base/share/classes/java/time/Duration.java#L283) and associated mod.

The test coverage in
[`TCKDuration`](https://github.com/openjdk/jdk/blob/8d9a4b43f4fff30fd217dab2c224e641cb913c18/test/jdk/java/time/tck/java/time/TCKDuration.java#L780) is already very thorough so no new tests are needed.

-------------

Commit messages:
 - 8318051: Avoid try/catch in Duration.between

Changes: https://git.openjdk.org/jdk/pull/16318/files
 Webrev: https://webrevs.openjdk.org/?repo=jdk&pr=16318&range=00
  Issue: https://bugs.openjdk.org/browse/JDK-8318051
  Stats: 32 lines in 1 file changed: 17 ins; 14 del; 1 mod
  Patch: https://git.openjdk.org/jdk/pull/16318.diff
  Fetch: git fetch https://git.openjdk.org/jdk.git pull/16318/head:pull/16318

PR: https://git.openjdk.org/jdk/pull/16318


More information about the core-libs-dev mailing list