Understanding Concurrency with Synchronize, Volatile, and Atomic!

Shubham Kumar Gupta
3 min readMay 1, 2024

Concurrency in Android development refers to the ability of an application to execute multiple tasks simultaneously, which can improve performance and responsiveness.

However, managing concurrent access to shared resources can be a challenge, leading to problems such as data corruption and race conditions. This article will explore three key concepts in Android concurrency: Synchronize, Volatile, and Atomic. We will also learn when to use each approach effectively.

1️⃣ Synchronize: Think of it as a polite traffic cop. It ensures one car (thread) passes through the intersection at a time. It keeps things orderly but can slow down the overall traffic.

Ensures thread safety by locking the critical section. It ensures that only one thread can access the synchronized block at a time, preventing data corruption.

For example, when multiple threads access and modify shared variables concurrently, Synchronize helps maintain order and consistency by allowing only one thread to execute the synchronized block at a time.

class Example {
private var counter = 0

fun increment() {
synchronized(this) {
counter++
}
}

fun getValue(): Int {
synchronized(this) {
return counter
}
}
}

In the above code, the synchronized block ensures that only one thread can execute either the increment or getValue function at a time, guaranteeing thread safety.

2️⃣ Volatile: This one’s like a shared bulletin board. Any update pinned on it is immediately seen by everyone passing by.

Changes made by one thread are immediately visible to others.

For instance, in scenarios where a flag variable controls the execution of a background thread, Volatile ensures that changes made by one thread to the flag variable are immediately visible to other threads.

@Volatile
private var running = false

fun startThread() {
Thread {
running = true
while (running) {
// Do some work
}
}.start()
}

fun stopThread() {
running = false
}

In this code, the @Volatile annotation ensures that the running variable is immediately visible to all threads, allowing proper synchronization-free communication.

3️⃣ Atomic: It ensures actions are completed in one swift move or as an atomic operation. They provide thread-safe read and write, lock-free programming. So, multiple threads try to read or write the same variable simultaneously.

For example, in high-performance applications where multiple threads need to increment or access a shared counter variable concurrently,

val counter = AtomicInteger(0)

fun incrementCounter() {
counter.incrementAndGet()
}

fun getCurrentValue(): Int {
return counter.get()
}

In this code, AtomicInteger provides atomic operations for incrementing and getting the current value of the counter variable, ensuring thread safety without explicit synchronization.

𝗕𝘂𝘁 𝗛𝗼𝘄 𝗔𝘁𝗼𝗺𝗶𝗰 𝘄𝗼𝗿𝗸𝘀?

Using volatile and Unsafe class allows Atomic to achieve atomicity and thread safety.
The Unsafe class is considered unsafe because it provides low-level, direct access to memory and operations that can be error-prone if used improperly.

public class AtomicInteger extends Number implements java.io.Serializable {
private static final VarHandle VALUE; // write
private volatile int value; // read
}

abstract class VarHandle {
// Android-added: Using sun.misc.Unsafe for fence implementation.
private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
}

Choosing the Right Approach!

When managing concurrency in Android, it’s important to consider the specific requirements of your application. Use the Synchronize method if you need strict thread safety and mutual exclusion. If you want immediate visibility of changes in shared variables across threads, go for Volatile. And if you’re looking for efficient and thread-safe read/write operations without synchronization overhead, leverage Atomic operations.

By using Synchronize, Volatile, and Atomic effectively, developers can ensure smooth execution and optimal performance in concurrent environments.

About the Author

I’m a passionate Android developer who loves exploring tech. Feel free to chat on LinkedIn for Android-related stuff and more. Thank You for reading this!

--

--