🚀 Enrollments Open for Jetpack Compose Cohort 3 — 4 Weeks of Live Learning to Build Modern Android UIs 💚Join Now
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

  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

Want to master these concepts?

Join our live cohorts and build production-ready Android apps.

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

Limited slots available each month