Search code examples
javaqueuedelayjava.util.concurrent

getDelay(TimeUnit) associated with Delayed interface in java


To use a DelayQueue we need to implement the Delayed interface for the getDelay(TimeUnit unit) and compareTo() method and as per my understanding, the getDelay method will be called where the parameter TimeUnit enum is not fixed, it may be TimeUnit.MICROSECONDS, TimeUnit.NANOSECONDS,TimeUnit.SECONDS etc. So for instance if unit.convert(long,TimeUnit.MICROSECONDS) is used we are asking the long variable which is in MICROSECONDS format to convert to the one specified by caller of getDelay.

I have used unit.name() in the below implementation but everytime i see only it prints TimeUnit.NANOSECONDS why does it only print NANOSECONDS. It can be anything. I have been testing the code to see the difference for almost 7 hours now. can anyone explain this behavior?

public long getDelay(TimeUnit unit){
    System.out.println("i'm calling "+unit.name());   // Always TimeUnit.NANOSECONDS
    long diff=millis-System.currentTimeMillis();
    return unit.convert(diff,TimeUnit.MILLISECONDS);  // Asking to convert to the one specified by the caller
}

Solution

  • In general that may be the case for that interface, but it appears class DelayQueue only ever calls getDelay(TimeUnit.NANOSECONDS).

    Class DelayQueue says that

    Expiration occurs when an element's getDelay(TimeUnit.NANOSECONDS) method returns a value less than or equal to zero.

    So it makes sense that it would only ever call with TimeUnit.NANOSECONDS.

    Other classes may call the method with other arguments. It's also possible that other versions of DelayQueue call the method with other arguments, but you can verify this openjdk8 implementation does not.