package atomic;

import lombok.Getter;

import java.util.Objects;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class AtomicExample08 {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<DelayedEntry> queue = new DelayQueue<>();
        queue.add(new DelayedEntry("A", 1000L));
        queue.add(new DelayedEntry("B", 1000L));
        queue.add(new DelayedEntry("C", 1000L));
        queue.add(new DelayedEntry("D", 1000L));
        queue.add(new DelayedEntry("E", 1000L));
        queue.add(new DelayedEntry("F", 1000L));
        queue.add(new DelayedEntry("G", 1000L));
        queue.add(new DelayedEntry("H", 1000L));
        queue.add(new DelayedEntry("I", 1000L));

        // 非阻塞读取，立即返回但不移除头部元素，队列为空返回null
        assert queue.peek() != null;
        System.out.println(queue.peek().value);

        // 非阻塞读取，当队列为空或者头部元素未达到过期时间返回值为null
        System.out.println(Objects.requireNonNull(queue.poll()).value);

        // 最大阻塞单位时间，到达阻塞单位时间后，此刻为空或者头部元素未达到过期时间返回值为null，否则立即移出头部元素
        System.out.println(Objects.requireNonNull(queue.poll(3, TimeUnit.SECONDS)).value);

        // 会一直阻塞到队列中有元素，并且队列头部元素达到过期时间，之后从队列中移除并返回
        System.out.println(queue.take().value);
    }

    // 首先要实现Delayed接口
    @Getter
    static class DelayedEntry implements Delayed {
        private final String value;
        private final long time;

        private DelayedEntry(String value, long time) {
            this.time = time;
            this.value = value;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            long delta = time - System.currentTimeMillis();
            return unit.convert(delta, TimeUnit.MILLISECONDS);
        }


        @Override
        public int compareTo(Delayed o) {
            if (this.time < ((DelayedEntry) o).time) {
                return -1;
            } else if (this.time > ((DelayedEntry) o).time) {
                return 1;
            }
            return 0;
        }
    }
}
