ConcurrentLinkedDeque란 무엇인가?
예제를 살펴보기 전에 먼저 ConcurrentLinkedDeque에 대해 알아보겠습니다. ConcurrentLinkedDeque는 연결 리스트(linked nodes) 기반으로 구현된 무한(unbounded) 크기의 덱(Deque)입니다. 가장 큰 특징은 여러 스레드가 동시에 덱의 요소에 안전하게 접근하고 조작할 수 있다는 점입니다. 즉, 별도의 동기화 처리 없이도 멀티스레드 환경에서 데이터 일관성을 보장합니다.
이번 예제에서는 Android에서 ConcurrentLinkedDeque의 마지막 요소를 가져오는 방법을 단계별로 알아보겠습니다.
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>
위 코드에서는 ConcurrentLinkedDeque의 요소들을 화면에 표시하기 위해 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.ConcurrentLinkedDeque;
public class MainActivity extends AppCompatActivity {
ConcurrentLinkedDeque concurrentLinkedDeque;
String head;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
concurrentLinkedDeque = new ConcurrentLinkedDeque<String>();
final TextView actionEvent = findViewById(R.id.actionEvent);
concurrentLinkedDeque.add("sai");
concurrentLinkedDeque.add("ram");
concurrentLinkedDeque.add("krishna");
concurrentLinkedDeque.add("prasad");
actionEvent.setText("" + concurrentLinkedDeque);
actionEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
actionEvent.setText("" + concurrentLinkedDeque.getLast());
}
});
}
}위 코드에서 핵심은 getLast() 메서드입니다. 이 메서드는 덱의 마지막(꼬리) 요소를 반환하되, 요소를 제거하지 않고 그대로 유지합니다. 만약 덱이 비어 있다면 NoSuchElementException이 발생하므로 주의해야 합니다.
애플리케이션 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run 아이콘을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 모바일 화면에 아래와 같은 기본 화면이 표시됩니다.

이제 화면의 TextView를 클릭하면 다음과 같이 마지막 요소가 결과로 출력됩니다.

덱에는 "sai", "ram", "krishna", "prasad" 순서로 요소가 추가되었으므로, getLast() 호출 시 가장 마지막에 삽입된 "prasad"가 화면에 표시됩니다.