androidengineers.Book a session
โ† All interview questions
ThreadIntermediate5 min

What is Thread Synchronization in Android?

Answer

What is Thread Synchronization?

Thread synchronization is a mechanism to control access to shared resources when multiple threads try to access them simultaneously. Without synchronization, you can get race conditions and data corruption.

Why is it Needed?

var counter = 0

// Thread 1 and Thread 2 both do this:
counter++  // Not atomic! Read -> Increment -> Write

// Without sync, final counter might be 1 instead of 2

Synchronization Techniques in Android/Kotlin

1. @Synchronized Annotation

@Synchronized
fun incrementCounter() {
    counter++
}

2. synchronized Block

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

3. Volatile Keyword

  • Ensures visibility across threads
  • Does NOT ensure atomicity
@Volatile
var isRunning = true

4. Atomic Classes

val atomicCounter = AtomicInteger(0)
atomicCounter.incrementAndGet()  // Thread-safe

5. ReentrantLock

val lock = ReentrantLock()

fun safeOperation() {
    lock.lock()
    try {
        // Critical section
    } finally {
        lock.unlock()
    }
}

6. Mutex (Kotlin Coroutines)

val mutex = Mutex()

suspend fun safeOperation() {
    mutex.withLock {
        // Critical section
    }
}

Visual: Race Condition

Without Sync:
Thread1: Read(0) -> Add -> Write(1)
Thread2:    Read(0) -> Add -> Write(1)  // Lost update!
Result: 1 (expected 2)

With Sync:
Thread1: Lock -> Read(0) -> Add -> Write(1) -> Unlock
Thread2:                                        Lock -> Read(1) -> Add -> Write(2) -> Unlock
Result: 2 โœ“

Best Practices

  1. Minimize lock scope - Only lock what's necessary
  2. Prefer higher-level abstractions - Use Coroutines with Mutex
  3. Use immutable data - Avoid shared mutable state
  4. Consider thread-safe collections - ConcurrentHashMap, CopyOnWriteArrayList

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising