Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Created January 14, 2023 22:00
Show Gist options
  • Save drmalex07/c4109377614a7f5b021b61d6cb7d5a68 to your computer and use it in GitHub Desktop.
Save drmalex07/c4109377614a7f5b021b61d6cb7d5a68 to your computer and use it in GitHub Desktop.
An example with DelayQueue in Java. #DelayQueue #java
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class DelayQueueExample
{
// A simple adapter for Delayed interface
static class DelayedItem <T> implements Delayed
{
private final T item;
private final long expiresAt;
DelayedItem(T item, long delayMillis)
{
this.item = item;
this.expiresAt = System.currentTimeMillis() + delayMillis;
}
public static <U> DelayedItem<U> of(U item, long delayMillis)
{
return new DelayedItem<U> (item, delayMillis);
}
public T getItem()
{
return item;
}
@SuppressWarnings("unchecked")
@Override
public int compareTo(Delayed other)
{
return Long.compare(expiresAt, ((DelayedItem<T>) other).expiresAt);
}
@Override
public long getDelay(TimeUnit unit)
{
final long delay = expiresAt - System.currentTimeMillis();
return unit.convert(Duration.ofMillis(delay));
}
}
public static void main(String[] args) throws Exception
{
final ExecutorService executor = Executors.newFixedThreadPool(2);
final DelayQueue<DelayedItem<String>> q = new DelayQueue<>();
final long delayMillis = 3000L;
executor.submit(new Callable<Integer>()
{
@Override
public Integer call() throws Exception
{
for (int i = 0; i < 10; i++) {
Thread.sleep(1000L + Math.round(Math.random() * 2000.0));
String msg = "hello" + String.valueOf(i + 1);
q.offer(DelayedItem.of(msg, delayMillis));
System.err.println("<< Added item: [msg=" + msg + "]");
}
return null;
}
});
executor.submit(new Callable<Integer>()
{
@Override
public Integer call() throws Exception
{
for (int i = 0; i < 10; i++) {
DelayedItem<String> d = q.take();
System.err.println(">> Received item: [msg=" + d.getItem() + "]");
}
return null;
}
});
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
System.err.println("Done");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment