I'm just starting out coding in java i'm in struggling with setting up a DelayQueue,
I wanted to have it so,
DelayQueue queue = new DelayQueue();
If (counter > 0){
queue.offer(Integer, *A custom delay*)
} Else {
queue.offer(Integer, *A different custom delay*)
}
I'm just trying to learn all the basics and ive read over the API and cant seem to grasp it.
Thanks in advance
Your "custom delay" classes must return the delay from the
getDelay(TimeUnit timeUnit)
method specified in theDelayed
interface. E.g.Note that you also need to provide an implementation for
compareTo()
.this implementation of
Delayed
is good because:compareTo()
does not do any class casting, eliminatig the possibility of throwing aClassCastException
compareTo()
usesMath.min
andMath.max
functions before casting toint
in order to properly prevent overflow errorsgetDelay()
properly converts the units and actually returns the time remainingTestDelay
class implementsDelayed
:JUnit unit test showing an example of using the
TestDelay
class:output of
DelayQueueTest
:The
DelayQueue
keeps the elements internally until a certain delay has expired. The elements must implement the interfacejava.util.concurrent.Delayed
.For example I have created a class
DelayedTest
extending Delayed interface. This will implement compareTo and getDelay() methodResult: