HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
자바 콜렉션
자바 콜렉션
/
BlockingQueue
BlockingQueue
BlockingQueue

BlockingQueue

BlockingQueue A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
 
BlockingQueue는 Queue의 기본 연산 - Insert, Remove, Examine 를 4가지 형태로 제공합니다.
 
  1. 첫번째 형태는 연산을 처리할 수 없는 경우 예외를 발생시킵니다. (add, remove, element)
  1. 두번째 형태는 특별한 값(null 혹은 false)을 반환합니다. (offer, poll, peek)
  1. 세번째 형태는 연산을 처리할 수 있을때 까지 현재 쓰레드를 blocking 합니다.
  1. 네번째 형태는 연산을 처리할 수 있을 시간 까지 blocking하는 시간을 설정할 수 있습니다.
 
ㅤ
1번 타입
2번 타입
3번 타입
4번 타입
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
 
  • BlockingQueue 는 null element를 허용하지 않습니다.
    • null은 poll( ) 메소드의 보초 값(sentinel value)으로 활용됩니다.
    •  
  • BlockingQueue는 capacity bound를 가질 수 있습니다.
    • remainingCamacity( )메소드는 blocking 없이 put(e) 할 수 있는 개수를 리턴합니다.
    • 따로 설정하지 않으면 capacity는 Integer.MAX_VALUE 입니다.
    •  
  • BlockingQueue는 Producer-Consumer Queues를 위해 디자인 되었습니다.
    • 하지만 Collection interface를 지원하기 때문에 직접적인add(e) remove( ), element( )의 호출은 가능하지만 보통 효율적이지 않습니다. 정말 필요할 때만 가끔 활용해야합니다.
 
  • BlocingQueue의 구현은 thread-safe합니다.
    • 모든 queing methods는 internal lock 혹은 다른 동시성 제어를 통해 atmoic 하게 동작합니다.
    • 하지만 addAll, containsAll, retainsAll and removeAll과 같은 bulk collection operations들은 thread-safe를 보장하지 않습니다.
 
  • BlockingQueue의 drainTo 메소드
    • int drainTo(Collection<? super E> c)
      • BlockingQueue → Collection 전부 drain
    • int drainTo(Collection<? super E> c, int maxElements)
      • BlockingQueue → Collection maxElements 개 만큼 drain

BlockingQueue를 활용한 Producer Consumer 예제

Jakob Jenkov - Java BlockingQueue