Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
222: Atomic Types from Kotlin
Why can't I just use a regular Int with @Volatile?
I get this question a lot. It seems logical: if @Volatile ensures that every thread sees the most recent value of a variable, why do we need these specialized atomic types? Here is the catch: visibility is not the same as atomicity.
Take a simple count++ operation. To the compiler, that's actually three separate steps: read the value, add one to it, and then write it back. If two threads do this at the exact same time, they might both read "5", both increment it to "6", and both write "6" back. You just lost an update. @Volatile doesn't stop that race condition; it only ensures that once the write happens, other threads see it immediately.
Atomic types, like AtomicInteger, handle that entire read-modify-write cycle as a single, uninterrupted operation at the hardware level. No locks, no synchronized blocks, just a clean, atomic jump from 5 to 6.
How do I actually use these in a real scenario?
Imagine you're building a high-throughput API and you want to track how many requests your server has handled since it started. You can't use a regular Int because you'll have dozens of threads hitting that counter simultaneously. You also don't want to use a synchronized block because that would force every single request to wait in line just to increment a number, which kills your performance.
import java.util.concurrent.atomic.AtomicInteger class RequestTracker { // We use AtomicInteger for lock-free thread safety private val totalRequests = AtomicInteger(0) fun trackRequest() { // incrementAndGet() is the atomic version of ++count val currentCount = totalRequests.incrementAndGet() println("Request #$currentCount processed") } fun getTotal(): Int = totalRequests.get() }In this snippet,
incrementAndGet()does the heavy lifting. It tells the CPU: "Update this value, and don't let anyone else touch it until this specific addition is done." It's incredibly fast compared to traditional locking.What is compareAndSet and why is it so important?
If you really want to master atomic types, you have to understand
compareAndSet(often called CAS). This is the "secret sauce" that makes lock-free programming possible. Instead of saying "set this value to X," you say, "set this value to X, but only if it is currently Y."I like to think of it as a "guarded update." If the value changed while you were calculating the new one, the operation fails, and you can decide what to do (usually by trying again in a loop). Here is a quick example of how you might use it to update a shared state only if it hasn't been modified by someone else:
import java.util.concurrent.atomic.AtomicReference sealed class AppState { object Initializing : AppState() object Ready : AppState() object ShuttingDown : AppState() } class StateManager { private val state = AtomicReference<AppState>(AppState.Initializing) fun markAsReady() { // Only move to 'Ready' if we are currently 'Initializing' val success = state.compareAndSet(AppState.Initializing, AppState.Ready) if (success) { println("System transitioned to Ready") } else { println("System was already modified or in a different state!") } } }Can I use these for my own custom objects?
Absolutely. That's exactly what
AtomicReferenceis for. WhileAtomicIntegerandAtomicBooleanhandle primitives,AtomicReferencecan wrap any object.The most common pattern I use with
AtomicReferenceis for "copy-on-write" updates. If you have a configuration object that rarely changes but is read constantly, you can wrap it in anAtomicReference. When it's time to update the config, you create a new version of the object and swap the reference atomically. This way, your readers never see a "half-updated" configuration object, and they never have to wait for a lock.
📋 Practical Task
Exercise: Thread-Safe Concurrent Event Counter
You are building a telemetry system that counts different types of events (e.g., "clicks", "views", "errors") across multiple background threads. Using a standard HashMap<String, Int> would cause a ConcurrentModificationException or lose data.
Your Task: Create a class called EventTelemetry that does the following:
- Uses a
ConcurrentHashMapwhere the values areAtomicIntegerobjects. - Implements a function
recordEvent(eventName: String). This function should check if the event exists in the map; if it does, increment its value. If it doesn't, it should create a newAtomicIntegerstarting at 1. - Implements a function
getEventCount(eventName: String): Intthat returns the current count for a specific event, or 0 if it has never been recorded.
Hint: Look into the computeIfAbsent method of ConcurrentHashMap to ensure the creation of the AtomicInteger itself is also thread-safe.
There are no comments for now.