1단계 미션을 보면 예약 상태를 관리할 때, AtomicLong을 쓴다. 그냥 Long을 써도 될 것 같은데 왜 AtomicLong을 쓸까?
학습 범위: AtomicLong을 Long 대신 쓰는 이유
AtomicLong의 사용방법, 원리에 대해서는 학습하지 않는다.
나의 가설: AtomicLong이라는 이름으로 비추어봤을 때, 원자성을 보장하는 Long 타입인 것 같다. 원자성이란 일련의 작업들이 모두 성공하거나 모두 실패하는 특성을 말한다. 동시에 여러 스레드가 수정해도 순차적으로 반영시켜주는 타입이라고 생각한다.
실제로 해보기
10개의 스레드가 1부터 10000까지 1씩 증가하는 코드
import java.util.concurrent.atomic.AtomicLong;
public class AtomicLongTest {
static long normalCount = 0;
static AtomicLong atomicCount = new AtomicLong(0);
static final int THREAD_COUNT = 10;
static final int INCREMENT_COUNT = 100_000;
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < INCREMENT_COUNT; j++) {
normalCount++;
atomicCount.incrementAndGet();
}
});
}
for (Thread thread : threads) thread.start();
for (Thread thread : threads) thread.join();
long expected = (long) THREAD_COUNT * INCREMENT_COUNT;
System.out.println("기대값: " + expected);
System.out.println("normalCount: " + normalCount);
System.out.println("atomicCount: " + atomicCount.get());
}
}
