Questions
ThreadIntermediate5 min
What is Thread Synchronization in Android?
SynchronizationConcurrency
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
- Minimize lock scope - Only lock what's necessary
- Prefer higher-level abstractions - Use Coroutines with Mutex
- Use immutable data - Avoid shared mutable state
- Consider thread-safe collections - ConcurrentHashMap, CopyOnWriteArrayList
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚