PriorityBlockingQueue란 무엇인가?
예제를 살펴보기 전에 PriorityBlockingQueue에 대해 먼저 이해해 보겠습니다. PriorityBlockingQueue는 무제한(unbounded) 큐로, 우선순위 큐(Priority Queue)와 동일한 순서 규칙을 따릅니다. 즉, 요소들이 단순히 삽입된 순서가 아니라 우선순위에 따라 정렬되어 처리됩니다.
이 큐의 가장 큰 특징은 스레드 안전(thread-safe)하다는 점입니다. 여러 스레드가 동시에 큐에 접근하더라도 데이터 일관성이 보장되며, 큐가 비어 있을 때 요소를 꺼내려는 시도가 발생하면 해당 스레드는 자동으로 대기 상태에 들어갑니다. 또한 내부적으로 용량을 동적으로 확장하기 때문에 메모리 부족(Out of Memory) 오류를 효과적으로 관리할 수 있습니다.
take() 메서드란?
take() 메서드는 큐의 맨 앞에서 우선순위가 가장 높은 요소를 검색하고 제거하는 역할을 합니다. 만약 큐가 비어 있다면, 새로운 요소가 추가될 때까지 현재 스레드를 무기한 대기시킵니다. 이러한 특성 덕분에 생산자-소비자(Producer-Consumer) 패턴 구현 시 매우 유용하게 활용됩니다.
이번 예제에서는 Android의 PriorityBlockingQueue에서 take() 메서드를 사용하는 방법을 알아보겠습니다.
구현 단계
1단계: 새 프로젝트 생성
Android Studio에서 File ⇒ New Project로 이동하여 새 프로젝트를 생성하고, 필요한 모든 세부 정보를 입력합니다.
2단계: 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
xmlns:app = "https://schemas.android.com/apk/res-auto"
xmlns:tools = "https://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<TextView
android:id = "@+id/actionEvent"
android:textSize = "40sp"
android:layout_marginTop = "30dp"
android:layout_width = "wrap_content"
android:layout_height = "match_parent" />
</LinearLayout>
위 코드에서는 PriorityBlockingQueue의 요소들을 화면에 표시하기 위해 TextView 하나를 배치했습니다.
3단계: MainActivity 코드 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.util.concurrent.PriorityBlockingQueue;
public class MainActivity extends AppCompatActivity {
PriorityBlockingQueue priorityBlockingQueue;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
priorityBlockingQueue = new PriorityBlockingQueue();
final TextView actionEvent = findViewById(R.id.actionEvent);
priorityBlockingQueue.add("sai");
priorityBlockingQueue.add("ram");
priorityBlockingQueue.add("krishna");
priorityBlockingQueue.add("prasad");
priorityBlockingQueue.add("ram");
actionEvent.setText("" + priorityBlockingQueue);
actionEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
actionEvent.setText("" + priorityBlockingQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
코드 설명
위 코드의 핵심 로직을 살펴보면 다음과 같습니다.
- 먼저 PriorityBlockingQueue 인스턴스를 생성하고, "sai", "ram", "krishna", "prasad", "ram" 다섯 개의 문자열 요소를 추가합니다.
- 큐에 추가된 요소들은 자동으로 사전순(알파벳 순)으로 정렬됩니다.
- TextView에는 초기 상태의 큐 전체 목록이 표시됩니다.
- TextView를 클릭하면 take() 메서드가 호출되어, 우선순위가 가장 높은(사전순으로 가장 앞선) 요소 하나를 꺼내 화면에 표시합니다.
take() 메서드는 InterruptedException을 발생시킬 수 있으므로 반드시 try-catch 블록으로 감싸 예외를 처리해야 합니다.
애플리케이션 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바에서 Run 아이콘을 클릭하세요. 그런 다음 모바일 기기를 선택하면 기기에 기본 화면이 표시됩니다.
앱이 실행되면 큐에 저장된 정렬된 요소 목록이 화면에 나타납니다.
이제 TextView를 클릭하면 take() 메서드에 의해 가장 우선순위가 높은 요소가 추출되어 결과가 아래와 같이 표시됩니다.
마무리
PriorityBlockingQueue의 take() 메서드는 멀티스레딩 환경에서 안전하게 우선순위 기반 작업 처리를 구현할 수 있는 강력한 도구입니다. 큐가 비어 있을 때 자동으로 대기하는 블로킹(blocking) 특성 덕분에 별도의 동기화 처리 없이도 안정적인 생산자-소비자 구조를 만들 수 있습니다. 작업 스케줄링, 태스크 큐 관리 등 다양한 시나리오에서 활용해 보시기 바랍니다.