Skip to Content
Course content

222: Atomic Types from Kotlin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 AtomicReference is for. While AtomicInteger and AtomicBoolean handle primitives, AtomicReference can wrap any object.

The most common pattern I use with AtomicReference is for "copy-on-write" updates. If you have a configuration object that rarely changes but is read constantly, you can wrap it in an AtomicReference. 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 ConcurrentHashMap where the values are AtomicInteger objects.
  • 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 new AtomicInteger starting at 1.
  • Implements a function getEventCount(eventName: String): Int that 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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.