Java

Java

Made by DeepSource

Duration.withNanos() may not produce correct results JAVA-E1087

Bug risk
Major

Using Duration.withNanos() may produce wrong results, because it will only set the value of the nanoseconds field of the duration, and will not correctly adjust for any overflow.

Bad Practice

Duration d = Duration.of(2, ChronoUnit.SECONDS);
// Any overflow from nanos to seconds will not be handled!
d = d.withNanos(extraNanoseconds);

Recommended

Use the two-argument overload of Duration.ofSeconds() instead.

Duration d = Duration.ofSeconds(2, extraNanoseconds);

Exceptions

This rule will respect suppress annotations like @SuppressWarnings("JavaDurationWithNanos") applied to the enclosing block or declaration.

References