|
| 1 | +package com.baeldung.concurrent.priorityblockingqueue; |
| 2 | + |
| 3 | +import org.assertj.core.api.Assertions; |
| 4 | +import org.junit.Test; |
| 5 | + |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.concurrent.PriorityBlockingQueue; |
| 8 | +import java.util.concurrent.TimeUnit; |
| 9 | +import java.util.stream.IntStream; |
| 10 | + |
| 11 | +import static org.assertj.core.api.Assertions.assertThat; |
| 12 | +import static org.assertj.core.util.Lists.newArrayList; |
| 13 | + |
| 14 | +public class PriorityBlockingQueueUnitTest { |
| 15 | + |
| 16 | + @Test |
| 17 | + public void shouldOrderQueue_whenPolling() throws InterruptedException { |
| 18 | + PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>(); |
| 19 | + ArrayList<Integer> polledElements = new ArrayList<>(); |
| 20 | + |
| 21 | + queue.add(1); |
| 22 | + queue.add(5); |
| 23 | + queue.add(2); |
| 24 | + queue.add(3); |
| 25 | + queue.add(4); |
| 26 | + |
| 27 | + polledElements.add(queue.poll()); |
| 28 | + polledElements.add(queue.poll()); |
| 29 | + polledElements.add(queue.poll()); |
| 30 | + polledElements.add(queue.poll()); |
| 31 | + polledElements.add(queue.poll()); |
| 32 | + |
| 33 | + assertThat(polledElements).containsExactly(1, 2, 3, 4, 5); |
| 34 | + } |
| 35 | + |
| 36 | + @Test |
| 37 | + public void shouldBlockThread_WhenPollingEmptyQueue() throws InterruptedException { |
| 38 | + PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>(); |
| 39 | + |
| 40 | + final Thread thread = new Thread(() -> { |
| 41 | + System.out.println("Polling..."); |
| 42 | + while (true) { |
| 43 | + try { |
| 44 | + Integer poll = queue.take(); |
| 45 | + System.out.println("Polled: " + poll); |
| 46 | + } catch (InterruptedException e) {} |
| 47 | + } |
| 48 | + }); |
| 49 | + thread.start(); |
| 50 | + |
| 51 | + Thread.sleep(TimeUnit.SECONDS.toMillis(5)); |
| 52 | + System.out.println("Adding to queue"); |
| 53 | + |
| 54 | + queue.addAll(newArrayList(1, 5, 6, 1, 2, 6, 7)); |
| 55 | + Thread.sleep(TimeUnit.SECONDS.toMillis(1)); |
| 56 | + } |
| 57 | +} |
0 commit comments