logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramlinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Atomic CASGlobal Lock OrderingRead Write SynchronizationReadWriteLock vs synchronized vs ReentrantLock60-Day LLD & Machine Coding Mastery Roadmap
The Four Pillars of OOPComposition, Asociation & AggregationDatabase locking / atomic updates
Don't Repeat Yourself (DRY) PrincipleKeep it Simple, Stupid (KISS) PrincipleYou Aren't Gonna Need It (YAGNI) Principle
Design a Library Management System (LMS)Design a Parking LotVending Machine
D : Dependency InversionI : The Interface Segregation PrincipleL : The Liskov Substitution PrincipleO : The Open/Closed PrincipleS : The Single Responsibility Principle
UML Activity Diagrams: Modeling Process and WorkflowUML Class Diagrams: Static Structure ModelingUML Sequence Diagrams: Modeling Dynamic InteractionsUse Case Diagrams: Functional Requirement Modeling
Low Level Design

Atomic CAS

1 min read

If we want to avoid traditional lock-based mutual exclusion for a very small state update atomic variables and CAS come into the picture.

CAS stands for Compare-And-Set (also commonly called Compare-And-Swap) it is an atomic operation that conceptually does three things:

  1. Read the current value.
  2. Compare it with an expected value.
  3. If it matches, replace it with a new value. The comparison and replacement happen as one indivisible operation.

Multiple threads can execute concurrently, but only one wins the atomic update. There is no explicit application-level lock around the operation.

CAS-based retry algorithms can be lock-free, but a CAS loop is not automatically wait-free. A particular thread might repeatedly lose the race and retry.

ABA problem

Suppose a thread reads a value A. Before it performs CAS, another thread changes the value A → B → A the original thread checks the value and sees A again. It assumes nothing changed, even though the state changed in between.

One mitigation is a version or stamp:

  (A, version 1)
  → (B, version 2)
  → (A, version 3)
Next→Global Lock Ordering