자바 Atomic 패키지
'java.util.concurrent.atomic' 패키지는 멀티스레드 환경에서 안전하게 변수를 조작할 수 있도록 하는 클래스를 제공한다.
Atomic 패키지를 정리하게 된 계기는 다음과 같다.
- 멀티 스레드를 사용하게 됨
- 각 멀티 스레드 수행 간 조건에 의해 static count를 증가시켜야 함
지역변수로 카운트 증가를 하려고 하니 스레드 세이프 하지 않아서 결과값이 기대처럼 안 나왔다.
이거 저거 알아보다가 Atomic 패키지가 있는 것을 알아냈다.
바로 예시를 들어가보자
package org.example.atomic;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicTest {
static Integer integer = 0;
public static void main(String[] args) {
// AtomicInteger 객체 생성
AtomicInteger atomicInt = new AtomicInteger(0);
// 여러 스레드에서 동시에 증가 연산 수행
Runnable incrementTask = () -> {
for (int i = 0; i < 1000; i++) {
integer++;
atomicInt.incrementAndGet();
}
};
// 스레드 생성
Thread thread1 = new Thread(incrementTask);
Thread thread2 = new Thread(incrementTask);
// 스레드 시작
thread1.start();
thread2.start();
try {
// 메인 스레드에서 생성한 스레드들이 모두 종료될 때까지 대기
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 결과 출력
System.out.println("Final atomicInt value: " + atomicInt.get());
System.out.println("Final integer value : " + integer);
}
}
// 출력 결과
// Final atomicInt value: 2000
// Final integer value : 1290
수행하는 것은 간단하다.
- 스레드 2개를 생성
- 각 스레드는 1000의 카운트를 증가시킨다.
- static 으로 선언된 integer와 AtomicInteger 를 비교한다.
결과는 atomicInt 는 2000, static Integer는 1290으로 나온 것을 볼 수 있다.
(static Integer 실행할 때마다 바뀜)
Integer타입도 있지만 boolean 타입 등 여러 타입이 있다.
상황에 맞게 사용하면 된다.
이처럼 멀티 스레드 환경에서 동기화 시킬 때 atomic 패키지를 활용하는 것도 좋은 방법이다.
'자바' 카테고리의 다른 글
[JDBC] DB PK변경 방법 (0) | 2024.02.07 |
---|---|
스프링 테스트 코드 @RestControllerAdvice를 거치게 하는 방법 (0) | 2024.01.25 |
JVM (Java Virtual Machine) (0) | 2024.01.18 |
자바(JAVA) - synchronized 란? (0) | 2024.01.16 |
객체 지향 4대 특성 간단 정리 (0) | 2022.09.07 |