컴퓨터 관련/Java 정보
AtomicLong 클래스
보뇨
2018. 2. 13. 09:51
반응형
공부하던중에 AtomicLong 클래스에 대해 전무하기 때문에 글을 올립니다 :)
AtomicLong 의 정의는 아래와 같이 뭐뭐뭐 라는 뜻인데 해석하자면 더이상 쪼개지지않는 최소단위로 읽거나 쓸수있는 클래스라는건데...
The AtomicLong
class provides you with a long
variable which can be read and written atomically, and which also contains advanced atomic operations like compareAndSet()
.
일단 예제를 쓰면서 알아가보자
클래스 선언은 아래와 같다
1 | AtomicLong atomicLong = new AtomicLong(123); | cs |
그리고 선언한것을 다른 인스턴스 변수에 대입하는것도 가능!
1 2 3 | AtomicLong atomicLong = new AtomicLong(123); long theValue = atomicLong.get(); | cs |
이런식으로 세팅도 가능하구
1 2 3 | AtomicLong atomicLong = new AtomicLong(123); atomicLong.set(234); | cs |
그리고 이건 좀 특이한건데 일단 그림을 먼저 보자
atomiclong 은 생성과정에서 인자값으로 123 을 받았는데 이것은 expectedValue 의 값과 동일하다. 그렇기때문에 증복된 값을 나타내는 변수를 가질필요가 없기때문에 compareAndSet을 통해 자신과 다른 newValue 값을 가지게 된다. compareAndSet 메서드는 기본적으로 bool 타입으로 출력해주기때문에 아래와 같이 5번줄처럼 쓸경우 true 가 나오고 하나라도 맞는 수가 없을경우 false 를 반환하게된다.
1 2 3 4 5 | AtomicLong atomicLong = new AtomicLong(123); long expectedValue = 123; long newValue = 234; atomicLong.compareAndSet(expectedValue, newValue); | cs |
마지막으로 산수처럼 쓰이는 클래스이다보니 산수와 관련된 메서드들도 있다. 좀 특이한것은 아래 메서드들 이름 가운데 and 가 있는데 이건 i++, i-- 로 쓰이는것이다.
1 2 3 4 5 6 7 | addAndGet() getAndAdd() getAndIncrement() incrementAndGet() decrementAndGet() getAndDecrement() | cs |
반응형