| 1 | package net.minecraft.util.thread;
|
| 2 |
|
| 3 | import com.google.common.collect.Queues;
|
| 4 | import java.util.Locale;
|
| 5 | import java.util.Queue;
|
| 6 | import java.util.concurrent.atomic.AtomicInteger;
|
| 7 | import org.jspecify.annotations.Nullable;
|
| 8 |
|
| 9 | public interface StrictQueue<T extends Runnable> {
|
| 10 | @Nullable Runnable pop();
|
| 11 |
|
| 12 | boolean push(final T t);
|
| 13 |
|
| 14 | boolean isEmpty();
|
| 15 |
|
| 16 | int size();
|
| 17 |
|
| 18 | final class FixedPriorityQueue implements StrictQueue<StrictQueue.RunnableWithPriority> {
|
| 19 | private final Queue<Runnable>[] queues;
|
| 20 | private final AtomicInteger size = new AtomicInteger();
|
| 21 |
|
| 22 | public FixedPriorityQueue(final int size) {
|
| 23 | this.queues = new Queue[size];
|
| 24 |
|
| 25 | for (int i = 0; i < size; i++) {
|
| 26 | this.queues[i] = Queues.newConcurrentLinkedQueue();
|
| 27 | }
|
| 28 | }
|
| 29 |
|
| 30 | @Override
|
| 31 | public @Nullable Runnable pop() {
|
| 32 | for (Queue<Runnable> queue : this.queues) {
|
| 33 | Runnable task = queue.poll();
|
| 34 | if (task != null) {
|
| 35 | this.size.decrementAndGet();
|
| 36 | return task;
|
| 37 | }
|
| 38 | }
|
| 39 |
|
| 40 | return null;
|
| 41 | }
|
| 42 |
|
| 43 | public boolean push(final StrictQueue.RunnableWithPriority task) {
|
| 44 | int priority = task.priority;
|
| 45 | if (priority < this.queues.length && priority >= 0) {
|
| 46 | this.queues[priority].add(task);
|
| 47 | this.size.incrementAndGet();
|
| 48 | return true;
|
| 49 | } else {
|
| 50 | throw new IndexOutOfBoundsException(String.format(Locale.ROOT, "Priority %d not supported. Expected range [0-%d]", priority, this.queues.length - 1));
|
| 51 | }
|
| 52 | }
|
| 53 |
|
| 54 | @Override
|
| 55 | public boolean isEmpty() {
|
| 56 | return this.size.get() == 0;
|
| 57 | }
|
| 58 |
|
| 59 | @Override
|
| 60 | public int size() {
|
| 61 | return this.size.get();
|
| 62 | }
|
| 63 | }
|
| 64 |
|
| 65 | final class QueueStrictQueue implements StrictQueue<Runnable> {
|
| 66 | private final Queue<Runnable> queue;
|
| 67 |
|
| 68 | public QueueStrictQueue(final Queue<Runnable> queue) {
|
| 69 | this.queue = queue;
|
| 70 | }
|
| 71 |
|
| 72 | @Override
|
| 73 | public @Nullable Runnable pop() {
|
| 74 | return this.queue.poll();
|
| 75 | }
|
| 76 |
|
| 77 | @Override
|
| 78 | public boolean push(final Runnable t) {
|
| 79 | return this.queue.add(t);
|
| 80 | }
|
| 81 |
|
| 82 | @Override
|
| 83 | public boolean isEmpty() {
|
| 84 | return this.queue.isEmpty();
|
| 85 | }
|
| 86 |
|
| 87 | @Override
|
| 88 | public int size() {
|
| 89 | return this.queue.size();
|
| 90 | }
|
| 91 | }
|
| 92 |
|
| 93 | record RunnableWithPriority(int priority, Runnable task) implements Runnable {
|
| 94 | @Override
|
| 95 | public void run() {
|
| 96 | this.task.run();
|
| 97 | }
|
| 98 | }
|
| 99 | }
|
| 100 |
|