Java ArrayBlockingQueue 고급 가이드: 블로킹 큐와 스레드 안전 연산
Java ArrayBlockingQueue
Java ArrayBlockingQueue의 생성, 조작, 스레드 안전 사용법을 명확한 예제로 학습합니다.
ArrayBlockingQueue 클래스는 Java 컬렉션 프레임워크에서 배열로 뒷받침되는 고정 크기의 스레드 안전 큐를 제공합니다. BlockingQueue 인터페이스를 구현하여 생산자와 소비자가 블로킹 연산으로 조정할 수 있게 합니다.
ArrayBlockingQueue 생성하기
java.util.concurrent.ArrayBlockingQueue를 임포트하고 고정 용량으로 인스턴스화하세요:
ArrayBlockingQueue<Type> queue = new ArrayBlockingQueue<>(capacity);
Type은 요소 타입, capacity는 최대 크기입니다.
참고: 용량은 필수이며 큐의 고정 크기를 결정합니다.
ArrayBlockingQueue 핵심 메서드
이 클래스는 요소 삽입, 접근, 제거를 위한 BlockingQueue의 모든 메서드를 구현합니다. 가장 자주 쓰이는 연산은 다음과 같습니다.
요소 삽입
add(E e) – 요소 추가, 가득 차면 IllegalStateException 발생
offer(E e) – 요소 추가, 가득 차면 false 반환
ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);
animals.add("Dog");
animals.offer("Cat");
animals.offer("Horse");
System.out.println("ArrayBlockingQueue: " + animals);
출력: ArrayBlockingQueue: [Dog, Cat, Horse]
요소 접근
peek() – 제거 없이 헤드 조회, 비어있으면 null
iterator() – 큐의 fail-fast 이터레이터 제공
String head = animals.peek();
System.out.println("Head element: " + head);
Iterator<String> it = animals.iterator();
while (it.hasNext()) {
System.out.print(it.next() + ", ");
}
출력: Head element: Dog 뒤이어 요소 목록
요소 제거
remove() – 헤드 제거 및 반환, 비어있으면 NoSuchElementException
poll() – 헤드 제거 및 반환, 비어있으면 null
clear() – 큐 비우기
String removed1 = animals.remove();
String removed2 = animals.poll();
animals.clear();
System.out.println("Updated queue: " + animals);
출력: Updated queue: []
블로킹 연산: put()과 take()
이 메서드들은 생산자-소비자 패턴에 필수적입니다. 연산이 가능해질 때까지 블로킹하여 스레드 조정을 보장합니다.
put()
요소 삽입, 큐가 가득 차면 대기. InterruptedException 발생 가능.
try {
animals.put("Dog");
animals.put("Cat");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
take()
헤드 제거 및 반환, 큐가 비어있으면 대기. InterruptedException 발생 가능.
try {
String element = animals.take();
System.out.println("Removed: " + element);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
추가 편의 메서드
| 메서드 | 설명 |
contains(Object o) | 지정된 요소가 큐에 있으면 true 반환 |
size() | 현재 요소 수 반환 |
toArray() | 큐를 배열로 변환 |
toString() | 큐의 문자열 표현 |
왜 ArrayBlockingQueue를 사용하는가?
다음을 제공하기 때문입니다:
- 스레드 안전성: 동시 접근을 위한 내장 동기화
- 고정 크기: 무제한 메모리 증가 방지
- 블로킹 의미론: 생산자-소비자 조정 단순화
한 스레드가 소비자보다 느리게 생산하면 소비자가 자동으로 블로킹되어 바쁜 대기를 피하고 효율적인 CPU 사용을 보장합니다.