AtomicBoolean

최희창·2022년 7월 13일
0

Kotlin

목록 보기
9/13

AtomicBoolean

  • boolean 자료형을 가지고 있는 wrapping 클래스입니다.
  • 멀티쓰레드 환경에서 동시성을 보장합니다.
  • Compare-And-Swap을 이용하여 동시성을 보장합니다. 여러쓰레드에서 데이터를 write해도 문제가 없습니다.
  • synchronized 보다 적은 비용으로 동시성을 보장할 수 있습니다.

객체 생성

AtomicBoolean atomicBoolean = new AtomicBoolean();
AtomicBoolean atomicBoolean2 = new AtomicBoolean(true);
  • 초기값은 false이다.

get(), set(), getAndSet()

  • boolean 값을 변경하려면 set(boolean) 메서드를, 값을 읽으려면 get() 메서드를 사용해야 합니다.
AtomicBoolean atomicBoolean = new AtomicBoolean();

atomicBoolean.set(true);

System.out.println("value : " + atomicBoolean.get());
  • getAndSet(boolean)은 현재의 value를 리턴하고, 인자로 전달된 값으로 업데이트 합니다.

compareAndSet()

  • compareAndSet(expect, update)는 현재 값이 예상하는 값과 동일하다면 update 값으로 변경해주고 true를 리턴해 줍니다. 그렇지 않다면 데이터 변경은 없고 false를 리턴합니다.
boolean expected = true;
AtomicBoolean atomicBoolean = new AtomicBoolean(false);
System.out.println("success ? " + atomicBoolean.compareAndSet(expected, true));
System.out.println("value : " + atomicBoolean.get());
profile
heec.choi

0개의 댓글