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.
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
1. @Synchronized Annotation
@Synchronized
fun incrementCounter() {
counter++
}
2. synchronized Block
fun incrementCounter() {
synchronized(this) {
counter++
}
}
3. Volatile Keyword
@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
}
}
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 โ
Mark this when you can explain the answer in your own words.
Help fellow developers prepare for interviews
Sharing helps the Android community grow ๐