[Java] PriorityBlockingQueue
PriorityBlockingQueue, java.util.concurrent.PriorityBlockingQueue, PBQ, 동시성 우선순위 큐
정의
java.util.concurrent.PriorityBlockingQueue<E> 는 PriorityQueue 의 동시성 + blocking 버전. unbounded 힙 기반 BlockingQueue.
특징
- unbounded, 따라서
put이 절대 block 하지 않음 take만 큐가 비어 있을 때 block- 단일 ReentrantLock 으로 보호
- 원소는
Comparable또는Comparator에 따라 정렬
동작
public void put(E e) {
offer(e); // 절대 block 안 함, unbounded
}
public E take() throws InterruptedException {
lock.lockInterruptibly();
try {
while ((e = dequeue()) == null) notEmpty.await();
return e;
} finally { lock.unlock(); }
}
복잡도
| 작업 | 시간 |
|---|---|
offer/put | O(log n) |
take/poll | O(log n) |
peek | O(1) |
사용 예
우선순위 작업 스케줄러 (멀티 스레드)
BlockingQueue<Task> queue = new PriorityBlockingQueue<>(
100,
Comparator.comparingInt(Task::priority).reversed()
);
// Worker pool
for (int i = 0; i < 4; i++) {
new Thread(() -> {
while (true) {
Task t = queue.take(); // 우선순위 높은 것부터
process(t);
}
}).start();
}
// Producer
queue.put(new Task(urgent));
queue.put(new Task(normal));
함정
1. unbounded → OOM
producer 가 빠르고 consumer 가 느리면 메모리 무한 증가. 외부 backpressure 필요.
2. 순회 순서
iterator 가 정렬 순서를 보장하지 않는다 (PriorityQueue 처럼). 정렬된 결과가 필요하면 모두 poll 후 처리.
참고
이 글의 용어 (4개)
- [Java] BlockingQueuejava
- 정의 는 요소를 가져올 때 비어 있으면 대기, 넣을 때 가득 차 있으면 대기 하는 thread-safe 큐 인터페이스. 생산자-소비자 (producer-consumer) 패턴의 …
- [Java] PriorityQueuejava
- 정의 는 이진 힙 (binary heap) 기반의 구현. FIFO 가 아닌 우선순위 순서 로 원소를 꺼낸다. 기본은 min-heap, 의 자연 순서나 로 우선순위 결정. 가장 작…
- [Java] ReentrantLockjava
- 정의 는 키워드와 같은 상호 배제 (mutual exclusion) 를 제공하는 클래스 기반 락. JSR-166 (Java 5) 에서 추가됐다. "재진입 (reentrant)" …
- Blocking (블로킹)concurrency
- 정의 Blocking 은 호출이 결과가 준비될 때까지 호출 스레드를 멈춰두는 실행 방식. 멈춰 있는 동안 그 스레드는 다른 일을 할 수 없다. OS 가 스레드를 sleep 상태로…
💬 댓글