user12029024
user12029024

Reputation:

DelayQueue implementation in Java

I'm a beginner in understanding threads and concurrency package. Understood that to use java.util.concurrent.DelayedQueue we have to implement the java.util.concurrent.Delayed interface and it has a abstract method getDelay()

long getDelay(TimeUnit unit)

Returns the remaining delay associated with this object, in the given time unit.

@Override
public long getDelay(TimeUnit unit) {
    long diff = startTime - System.currentTimeMillis();  // long variable
    return unit.convert(diff, TimeUnit.MILLISECONDS);   // Not clear about this part which also returns long
}

All getDelay does is get the milliseconds difference which i believe we get from above diff variable then why do we need to use convert method? convert method says that diff needs to be converted to milliseconds (Why does it need to convert when it is already in milliseconds). TimeUnit is just for specifying that convert to milliseconds if my understanding is not wrong. Can anyone help me understand more on this topic.

EDIT-1

diff contains milliseconds difference and it is printed in the below screenshot console. Tried using convert method of Timeunit and also printed in the console below which are exactly same and are of long datatype. When both the values are same and long datatype why do i need to use this extra line of

unit.convert(diff, TimeUnit.MILLISECONDS);

instead i could also return the diff directly without using the convert method.

Console screenshot

Upvotes: 4

Views: 287

Answers (1)

user3453226
user3453226

Reputation:

unit is supplied by the caller of getDelay(). The implementation must return the delay in the time unit specified by unit.

Therefore, unit.convert(diff, TimeUnit.MILLISECONDS) converts diff, which is expressed in TimeUnit.MILLISECONDS, to unit.

TimeUnit.MILLISECONDS refers to what diff is. diff is then converted from TimeUnit.MILLISECONDS to unit.

Note that you must also implement compareTo() of Comparable, which Delayed extends.


The unit parameter is not fixed. It is supplied by the caller of the method, therefore it may vary. It may be TimeUnit.MILLISECONDS or TimeUnit.SECONDS or any other enum value. That's why you need to use the convert method.

Upvotes: 3

Related Questions