Java

[Java] AtomicInteger 사용하기

hyunki.Dev 2023. 1. 7. 17:48

오늘은 Java의 AtomicInteger에 대해 정리해보고자 합니다. 

 

AtomicInteger는 Java에서 제공하는 클래스로 

Java의 멀티스레드 환경에서 숫자 관련 계산을 진행할 때  자원의 동시성 제어를 위해 사용되는 클래스입니다.

이러한 AtomicInteger는 동기화된 int 보다 성능 역시 뛰어나다고 합니다.

 

-- Java의 멀티스레드 환경과 동시성 제어는 여기서 다루기엔 내용이 길어져 따로 정리해보도록 하겠습니다.

 

이번에 AtomicInteger를 알게 된 계기는 테이블의 데이터를 조회하여 해당 데이터를 정렬 후 점수에 따라 랭크를 부여해야 했습니다. 이때 AtomicInteger 클래스를 사용하여 처리한 팀원의 코드를 보고 찾아보게 되었습니다.


객체 생성

public void atomicInteger() {
    AtomicInteger atomicInteger = new AtomicInteger();
    System.out.println("value : " + atomicInteger.get());

    AtomicInteger atomicInteger2 = new AtomicInteger(10);
    System.out.println("value : " + atomicInteger2.get());
}
value : 0
value : 10

객체생성은 위와 같이 하면 됩니다. 

초기값은 0이며 다른 값으로 초기화를 하고 싶을 경우 인자로 해당 값을 넘겨 주면 됩니다.

 

get(), set(), getAndSet()

값을 불러오고 저장하는 것은 java에서 자주 활용하던 get, set 메서드를 활용하면 됩니다. 

public void atomicInteger() {
    AtomicInteger atomicInteger = new AtomicInteger();
    System.out.println("value : " + atomicInteger.get());

    atomic.set(50);
    System.out.println("value : " + atomicInteger.get());
}
value : 0
value : 50

 

getAndSet(int)은 우선 현재의 value를 리턴하고, 이후 인자로 전달된 값으로 업데이트합니다.

public void atomicInteger() {
    AtomicInteger atomicInteger = new AtomicInteger(10);
    System.out.println("value1 : " + atomicInteger.getAndSet(30));
    System.out.println("value2 : " + atomicInteger.get());
}
value1 : 10
value2 : 30

 

compareAndSet()

compareAndSet(expect, update)는 현재 값이 예상하는 값(expect)과 동일하다면 update 값으로 변경해주고 true를 리턴해 줍니다. 그렇지 않다면 데이터 변경은 없고 false를 리턴합니다.

 

/**
 * Atomically sets the value to the given updated value
 * if the current value {@code ==} the expected value.
 *
 * @param expect the expected value
 * @param update the new value
 * @return {@code true} if successful. False return indicates that
 * the actual value was not equal to the expected value.
 */
public final boolean compareAndSet(int expect, int update)
public void atomicInteger() {
    int expected = 30;
    AtomicInteger atomicInteger = new AtomicInteger(10);
    System.out.println("success ? " + atomicInteger.compareAndSet(expected, 100));
    System.out.println("value : " + atomic.get());

    atomic.set(30);
    System.out.println("success ? " + atomicInteger.compareAndSet(expected, 100));
    System.out.println("value : " + atomicInteger.get());
}
success ? false
value : 10
success ? true
value : 100

 

이외에도 유용하게 사용할 수 있느 다양한 AtomicInteger 관련 메서드들이 있으니 숫자 관련된 데이터 변경을 진행할 때 참고하시어 사용하시면 좋을 것 같습니다.

 

AtomicInteger atomic = new AtomicInteger(0);
int i = 0;
 
int x = 10;
int y;

y = atomic.get(); 와 동등하다 y = i;
y = atomic.incrementAndGet(); 와 동등하다 y = ++i;
y = atomic.getAndIncrement(); 와 동등하다 y = i++;
y = atomic.decrementAndGet(); 와 동등하다 y = --i;
y = atomic.getAndDecrement(); 와 동등하다 y = i--;
y = atomic.addAndGet(x); 와 동등하다 i = i + x; y = i;
y = atomic.getAndAdd(x); 와 동등하다 y = i; i = i + x;
atomic.set(x); 와 동등하다 i = x;
y = atomic.getAndSet(x); 와 동등하다 y = i; i = i + x;

 

 

 

참고: 

https://codechacha.com/ko/java-atomic-integer/

 

Java - AtomicInteger 사용 방법

AtomicInteger는 int 자료형을 갖고 있는 wrapping 클래스입니다. 멀티쓰레드 환경에서 동시성을 보장합니다. volatile과 다르게 여러 쓰레드에서 값을 write해도 동시성이 보장됩니다. get, set, getAndSet, compa

codechacha.com

https://www.techiedelight.com/ko/atomicinteger-class-java/

 

Java의 AtomicInteger 클래스

이 게시물은 AtomicInteger 여러 스레드에서 동시에 액세스할 수 있는 다중 스레드 환경에서 원자 정수 카운터로 사용할 수 있는 Java의 클래스입니다. 카운터를 증가시키는 것은 Java에서 스레드로부

www.techiedelight.com