You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
1. CAS 락 구현 1 - 문제점 확인
CAS 연산을 사용하지 않고 일반적인
volatile변수만으로 락을 구현했을 때 발생하는 동시성 문제를 확인SpinLockBad 클래스 (원자적이지 않은 구현)
lock()을 호출하면, 둘 다if(!lock)조건을 통과한 후 각각lock = true를 수행하게 됨1) 락 사용 여부 확인과2) 락의 값 변경이라는 두 연산이 하나의 원자적인 단위로 묶여 있지 않기 때문임2. CAS 락 구현 2 - 원자적 락 구현 (Spin Lock)
CAS 연산을 지원하는
AtomicBoolean을 사용하여 안전하고 가벼운 락을 구현할 수 있음SpinLock 클래스 (CAS 활용)
compareAndSet(false, true)를 사용하여 "락이false인 경우에만true로 바꿔라"라는 명령을 CPU 차원에서 원자적으로 수행하게 함3. 정리: 동기화 락(Lock) vs CAS
비교 요약 표
실무에서 사용할때
CAS가 유리한 경우
동기화 락이 유리한 경우
참고: 실무에서는 직접 CAS를 구현하기보다, 이미 CAS로 최적화된
AtomicInteger등 자바 표준 라이브러리를 잘 활용하는 것이 중요Beta Was this translation helpful? Give feedback.
All reactions