Created
January 12, 2022 11:12
-
-
Save ak-git/0edf178e5564005a82702f0e6fd0685d to your computer and use it in GitHub Desktop.
Delay Queue based on https://habr.com/ru/post/599603/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.ak.util; | |
import java.time.Duration; | |
import java.time.Instant; | |
import java.time.temporal.TemporalAmount; | |
import java.util.Random; | |
import java.util.concurrent.BlockingQueue; | |
import java.util.concurrent.DelayQueue; | |
import java.util.concurrent.Delayed; | |
import java.util.concurrent.TimeUnit; | |
import java.util.logging.Logger; | |
import javax.annotation.Nonnull; | |
import org.testng.annotations.Test; | |
public class DelayQueueTest { | |
record DelayedEvent(@Nonnull Instant future, @Nonnull String msg) implements Delayed { | |
DelayedEvent(@Nonnull TemporalAmount duration, @Nonnull String msg) { | |
this(Instant.now().plus(duration), msg); | |
} | |
@Override | |
public long getDelay(@Nonnull TimeUnit unit) { | |
return future.compareTo(Instant.now()); | |
} | |
@Override | |
public int compareTo(@Nonnull Delayed o) { | |
return future.compareTo(((DelayedEvent) o).future); | |
} | |
} | |
@Test(invocationCount = 3) | |
public void test() { | |
BlockingQueue<DelayedEvent> delayQueue = new DelayQueue<>(); | |
int randomSeconds = new Random().nextInt(10); | |
boolean offer = delayQueue.offer(new DelayedEvent(Duration.ofSeconds(randomSeconds), "1")); | |
Logger.getAnonymousLogger().info("Done %s, waiting for %d seconds".formatted(offer, randomSeconds)); | |
try { | |
Logger.getAnonymousLogger().info(delayQueue.take().msg()); | |
} | |
catch (InterruptedException e) { | |
Logger.getAnonymousLogger().warning(e::getMessage); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment