Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Duration.isZero() return false and yet Duration.toMillis() returns zero?

Tags:

java

In order to calculate a wait() duration, we do some math on Durations:

   Instant start = Instant.now();
   while(!exiting) {
       synchronized(waitObject)
       {
           Duration toWait = TOTAL_WAIT_TIME.minus(Duration.between(start, Instant.now()));
           if (!toWait.isNegative() && !toWait.isZero() {
               waitObject.wait(toWait.toMillis());
           }
       }
   }

Obviously there's more in this code, but that distills it to its basics for this question.

What we are seeing in our testing is that the argument being passed into wait() can be zero.

like image 400
nsayer Avatar asked Jan 22 '26 16:01

nsayer


1 Answers

This demonstrates your observation:

public class Main
{
    public static void main(String[] args) {

        Duration d = Duration.ofNanos(1);
        System.out.println("isZero=" + d.isZero());
        System.out.println("toMillis=" + d.toMillis());
    }
}

Output:

isZero=false
toMillis=0

Relevant docs from toMillis:

If this duration has greater than millisecond precision, then the conversion will drop any excess precision information as though the amount in nanoseconds was subject to integer division by one million.