[Java]AtomicReference

Yono·2024년 9월 10일

AtomicReference

AtomicReference는 자바의 java.util.concurrent.atomic 패키지에 속하는 클래스이다.

AtomicReference란??

AtomicReference는 객체 참조형 변수가 한번에 수정되어야 하는 상황에서 사용하는 클래스입니다. 즉, 여러 쓰레드가 동시에 같은 객체를 참
조하고, 그 값을 변경하려고 할 때 사용됩니다. 이때, 한 쓰레드가 값의 변경을 완료하기 전에 다른 쓰레드가 값을 읽으면 이전 버전의 값을
읽게 되는 문제(Dirty Read)가 발생할 수 있습니다.

AtomicReference는 이러한 문제를 해결하기 위해 원자성(atomicity)을 보장하는 클래스입니다. 즉, 한 쓰레드가 객체 참조형 변수를 수정하
는 연산은 다른 쓰레드에 의해 중간에 끊어지지 않으며, 완전히 수행된 후 다른 쓰레드는 그 결과를 읽을 수 있습니다.

AtomicReference의 유즈케이스는 다음과 같습니다:

  1. 서버 동기화: 여러 서버가 하나의 데이터베이스를 공유할 때, AtomicReference를 사용하여 각 서버가 같은 객체 참조형 변수를 수정
    하는 연산에서 원자성을 보장할 수 있습니다.
  2. 멀티쓰레드 환경: 여러 쓰레드가 동시에 하나의 객체 참조형 변수를 수정하려고 할 때, AtomicReference를 사용하여 원자성을 보장할
    수 있습니다.

사용 예

import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceExample {
    public static void main(String[] args) {
        // 원래의 값
        String originalValue = "원래의 값";

        // AtomicReference 생성
        AtomicReference<String> atomicReference = new AtomicReference<>();

        // AtomicReference에 원래의 값을 세팅
        atomicReference.set(originalValue);

        // 쓰레드 1이 AtomicReference의 값을 변경
        Thread thread1 = new Thread(() -> {
            String newValue = "쓰레드 1에서 변경한 값";
            atomicReference.set(newValue);
        });

        // 쓰레드 2가 AtomicReference의 값을 읽음
        Thread thread2 = new Thread(() -> {
            System.out.println("쓰레드 2에서 읽은 값: " + atomicReference.get());
        });

        // 쓰레드 실행
        thread1.start();
        thread2.start();

        // 쓰레드 종료
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("종료");
    }
}

다음 글은 AtomicReference vs Syncronized 해당 주제로 작성해 보겠다.

profile
Java,Spring,JavaScript

0개의 댓글