Skip to content

Avoid premature overflow when converting durations to microseconds - #52557

Merged
philwebb merged 1 commit into
spring-projects:4.0.xfrom
raunakpandey1:fix/duration-microseconds-overflow
Nov 3, 2026
Merged

philwebb merged 1 commit into
spring-projects:4.0.xfrom
raunakpandey1:fix/duration-microseconds-overflow

Conversation

@raunakpandey1

@raunakpandey1 raunakpandey1 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Converting a Duration to microseconds currently calls toNanos() before dividing by 1000. This throws ArithmeticException when the nanosecond count exceeds long, even if the microsecond count fits. It affects both DurationStyle.SIMPLE.print and duration-to-number conversion with @DurationUnit(MICROS).

For example, on current main (4.2.0-SNAPSHOT):

Duration duration = Duration.of(Long.MAX_VALUE, ChronoUnit.MICROS);
DurationStyle.SIMPLE.print(duration, ChronoUnit.MICROS);
// Expected: "9223372036854775807us"
// Actual: ArithmeticException: long overflow

Use Duration.dividedBy(Duration.ofNanos(1000)) to obtain the microsecond count directly. This supports the full long range, preserves truncation toward zero for fractional microseconds, and still throws when the microsecond result itself overflows.

Regression tests cover both signed limits (including fractional remainders), positive and negative submicrosecond truncation, genuine overflow, and number conversion through standalone and application conversion services.

Validation on Temurin JDK 25.0.5:

  • Before the fix: 46 tests in DurationStyleTests and DurationToNumberConverterTests, with four regression failures caused by the intermediate nanosecond overflow.
  • After the fix: all 271 tests in org.springframework.boot.convert.* passed, with no skips.
  • :core:spring-boot:checkFormat, :core:spring-boot:checkstyleMain, and :core:spring-boot:checkstyleTest passed.

@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue that has not yet been triaged. Contributions will not be accepted. label Nov 2, 2026
@philwebb philwebb added type: bug A general bug and removed status: waiting-for-triage An issue that has not yet been triaged. Contributions will not be accepted. labels Nov 3, 2026
@philwebb philwebb added this to the 4.0.x milestone Nov 3, 2026
@philwebb
philwebb force-pushed the fix/duration-microseconds-overflow branch from 6673daa to e620291 Compare November 3, 2026 00:31
@philwebb
philwebb changed the base branch from main to 4.0.x November 3, 2026 00:32
@philwebb philwebb modified the milestones: 4.0.x, 4.0.10 Nov 3, 2026
@philwebb
philwebb merged commit 9ef5b48 into spring-projects:4.0.x Nov 3, 2026
1 check passed
@philwebb

philwebb commented Nov 3, 2026

Copy link
Copy Markdown
Member

Thanks very much @raunakpandey1!

@raunakpandey1

Copy link
Copy Markdown
Contributor Author

Thanks @philwebb!
Looking forward to more contributions:)

@dobrosi

dobrosi commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

While that fix is brilliant, it introduces noticeable overhead due to multiple intermediate BigDecimal allocations.

I would suggest a slightly more verbose but significantly more efficient alternative:

/**
 * Microseconds.
 */
MICROS(ChronoUnit.MICROS, "us", (duration) -> {
    long seconds = duration.getSeconds();
    long nanos = duration.getNano();
    if (seconds < 0) {
        seconds++;
        nanos -= 1_000_000_000L;
    }
    return Math.addExact(Math.multiplyExact(seconds, 1_000_000L), nanos / 1_000L);
}),

This approach avoids heap allocations entirely, correctly truncates toward zero for negative durations (following the pattern in Duration.toMillis()), and safely throws an ArithmeticException on overflow via JIT-intrinsic Math.*Exact calls.

What do you think?

Thanks,

András Dobrosi

@wilkinsona

Copy link
Copy Markdown
Member

noticeable overhead due to multiple intermediate BigDecimal allocations

Can you provide an example? In what real-world situations is the overhead noticeable?

@dobrosi

dobrosi commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

I'm sharing this benchmark report with you:

https://github.com/dobrosi/duration-benchmark

Benchmark                                                 Mode  Cnt     Score      Error   Units
DurationBenchmark.dividedByBigDecimal                     avgt    3   259.980 ±  210.185   ns/op
DurationBenchmark.dividedByBigDecimal:gc.alloc.rate       avgt    3  3431.441 ± 2700.283  MB/sec
DurationBenchmark.dividedByBigDecimal:gc.alloc.rate.norm  avgt    3   936.002 ±    0.001    B/op
DurationBenchmark.dividedByBigDecimal:gc.count            avgt    3    43.000             counts
DurationBenchmark.dividedByBigDecimal:gc.time             avgt    3    44.000                 ms
DurationBenchmark.primitiveArithmetic                     avgt    3     1.586 ±    1.329   ns/op
DurationBenchmark.primitiveArithmetic:gc.alloc.rate       avgt    3     0.007 ±    0.001  MB/sec
DurationBenchmark.primitiveArithmetic:gc.alloc.rate.norm  avgt    3    ≈ 10⁻⁵               B/op
DurationBenchmark.primitiveArithmetic:gc.count            avgt    3       ≈ 0             counts

@wilkinsona

Copy link
Copy Markdown
Member

@dobrosi that's not a real-world situation, it's a non-representative microbenchmark. A real-world situation would be a Spring Boot app where the time taken by the code in question to convert durations to microseconds has a meaningful impact on performance.

@dobrosi

dobrosi commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

I understand your point of view, but in this technical matter, I prefer the more efficient approach. I consider this matter closed on my end.

@philwebb

philwebb commented Nov 3, 2026

Copy link
Copy Markdown
Member

I don't think the microseconds us suffix is commonly used in the wild, so we'll keep the simpler code and take the hit. Thanks anyway for suggestion.

@dobrosi

dobrosi commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Thank you. It's not just about the time; this solution doesn't quite fit this pattern.

The original toMillis() implementation is heapless but buggy, while the proposed fix is correct but allocates on the heap.

My solution (which, by the way, follows the OpenJDK approach for nanos, millis, etc.) handles everything in one place.

dividedBy() is a useful method, but it's not needed here.

Have a nice day, and good job!

@philwebb

philwebb commented Nov 4, 2026

Copy link
Copy Markdown
Member

@dobrosi Aligning with the JDK is quite a compelling argument so I've updated the code in 0032756. Thanks for push.

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-spring-projects__spring-boot that referenced this pull request Nov 4, 2026
Switch to an implementation aligned with the standard `Duration` code
to reduce heap usage.

See spring-projectsgh-52557
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: bug A general bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants