관리 메뉴

백엔드 엔지니어 이재혁

[Java] BlockingQueue 본문

Java

[Java] BlockingQueue

alex00728 2025. 5. 29. 19:12

java.util.concurrent 패키지에는 BlockingQueue 인터페이스가 있다.

 

대표적인 구현체

  • ArrayBlockingQueue
  • LinkedBlockingQueue

BlockingQueue의 메서드

Java 7 공식 문서에 있는 요약본

Operation Throws Exception Special Value Blocks Times Out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable

 

Throws Exception - 대기시 예외

  • add(e): e를 큐에 추가. 큐가 가득찬 상태면 IllegalStateException 예외 던짐.
  • remove(): 큐에서 요소를 제거하여 반환. 큐가 비어있으면 NoSuchElementException 예외 던짐.
  • element(): remove()와 달리 요소를 큐에서 제거하지 않는 메서드.

Special Value - 대기시 즉시 반환

  • offer(e): e를 큐에 추가. 큐가 가득 차면 false 반환
  • poll(): 큐에서 요소를 제거하여 반환. 큐가 비어있으면 null 반환
  • peek(): poll()과 달리 요소를 큐에서 제거하지 않는 메서드.

Blocks - 대기

  • put(e): e를 큐에 추가. 큐가 가득찬 상태면 공간이 생길 때까지 대기.
  • take(): 큐에서 요소를 제거하여 반환. 큐가 비어있으면 요소가 생길 때까지 대기.

Times Out - 시간 대기. Special Value 메서드에 시간 매개변수를 추가로 넘겨서 사용

 

BlockingQueue의 모든 대기, 시간 대기 메서드는 인터럽트가 가능.

 

참고

Interface BlockingDeque<E> extends BlockingQueue, Deque

Java는 Deque 자료구조를 위한 BlockingDeque 인터페이스도 제공한다.

 

'Java' 카테고리의 다른 글

[Spring] Spring이 작동하는 방식  (0) 2025.06.08
[Spring] Spring이 등장한 이유  (0) 2025.06.08
[Java] 생산자 소비자 문제 (2)  (0) 2025.05.27
[Java] 생산자 소비자 문제  (0) 2025.05.26
[Java] concurrent.locks  (0) 2025.05.23