웹 개발

Java - ArrayBlockingQueue 사용 방법

노루아부지 2021. 1. 1. 22:53

ArrayBlockingQueue는 Array로 구현된 BlockingQueue입니다. 특징은 아래와 같습니다.

 

  • BlockingQueue 인터페이스를 구현
  • Queue를 생성할 때 크기를 설정(Queue의 크기가 정해져 있음)
  • FIFO(First In First Out)로 동작
  • 아이템을 가져올 때 비어있으면 null을 리턴하지 않고 아이템이 추가될 때까지 wait
  • 아이템을 추가할 때 Queue가 가득 차 있으면 공간이 생길 때까지 wait 하거나 Exception이 발생하게 할 수도 있음
  • 동시성에 안전하기 때문에 멀티 쓰레드 환경에서 synchronized 구문 없이 사용 가능

 

 

 

ArrayBlockingQueue 생성

 

아래와 같이 간단하게 객체를 생성할 수 있습니다.

int capacity = 10;
ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);

 

아래와 같이 인자로 fair를 전달 할 수 있습니다.

/**
 * Creates an {@code ArrayBlockingQueue} with the given (fixed)
 * capacity and the specified access policy.
 *
 * @param capacity the capacity of this queue
 * @param fair if {@code true} then queue accesses for threads blocked
 *        on insertion or removal, are processed in FIFO order;
 *        if {@code false} the access order is unspecified.
 * @throws IllegalArgumentException if {@code capacity < 1}
 */
public ArrayBlockingQueue(int capacity, boolean fair) {
  
}

 

fair가 true라면 멀티 쓰레드 환경에서 FIFO로 처리됩니다. 반대로 false라면 정해진 규칙이 없습니다.

또한 다음과 같이 초기값까지 인자로 전달할 수 있습니다. 초기값은 Collection 객체로 전달하면 됩니다.

List<Integer> list = Arrays.asList(10, 20, 30);
int capacity = 10;
ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity, true, list)

 

 

 

add() : 아이템 추가

add() 메서드를 통해 Queue에 아이템을 추가할 수 있습니다.

만약 아래와 같이 Queue의 크기보다 더 많은 아이템을 추가하려고 하면 Exception이 발생합니다.

int capacity = 3;
ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);

try {
  queue.add(1);
  queue.add(2);
  queue.add(3);
  queue.add(4);
}
catch(Exception e) {
  e.printStackTrace();
}

 

Exception을 방지하기 위해서 remainingCapacity() 메서드를 이용할 수 있습니다. 이 메서드는 Queue의 여유 공간을 리턴해줍니다.

 

 

put()

put()은 Queue가 full일 때 Exception을 발생시키지 않고 여유 공간이 생길 때까지 무한히 기다립니다.

 

offer()

offer()는 Queue가 full일 때 Exception을 발생시키지 않고 false를 리턴합니다.

 

offer(timeout)

offer(timeout)은 설정한 시간만큼 기다리고, 정해진 시간 내에 여유 공간이 생기면 아이템을 추가합니다. timeout 시간 설정 단위는 millisecond입니다.

 

take()

take()는 Queue에서 아이템을 삭제하고 그 값을 리턴합니다. Queue가 empty일 때 take()를 호출하면 block 되고, 아이템이 추가될 때까지 기다립니다. 대기 중에 스레드에서 아이템이 추가되면 그 값을 리턴합니다. 대기 중에 InterruptedException가 발생할 수 있기 때문에 예외처리가 필요합니다.

 

poll(timeout)

poll(timeout)을 이용하여 아이템을 가져올 때 Timeout을 설정하여 무한히 기다리는 일이 발생하지 않도록 할 수 있습니다.

단위는 Timeout의 단위는 millisecond입니다.

728x90
loading