1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 5

CAP477 · Unit 5: Concurrency and I/O

Synchronization and thread safety

8 practice questions

Key points

  • synchronized gives mutual exclusion and visibility
  • volatile gives visibility only
  • wait/notify need the monitor
  • Deadlock = circular wait; fix with lock ordering

A race condition occurs when threads read and modify shared data without coordination, so n++ (read, add, write) can lose updates. The result of unsynchronised code is unpredictable and often lower than expected.

Tools:

  • `synchronized` method or block: only one thread at a time holds an object's monitor lock. Four threads each calling a synchronized void inc() 50,000 times always end at 200000. synchronized (obj) { ... } locks a chosen object; a static synchronized method locks the Class object.
  • Atomic classes (AtomicInteger): lock-free operations such as incrementAndGet, addAndGet, compareAndSet(expect, update).
  • `ReentrantLock`: explicit lock() and unlock(); always unlock in finally. Supports tryLock and fairness.
  • `volatile`: guarantees visibility (a write is seen by other threads) but not atomicity (count++ stays unsafe). Good for stop flags.
  • Concurrent collections: ConcurrentHashMap (thread-safe merge), CopyOnWriteArrayList (iteration sees a snapshot; adding during iteration is safe and the loop does not see 9), Collections.synchronizedList.

Inter-thread communication: wait(), notify(), notifyAll() must be called while holding the object's monitor, else IllegalMonitorStateException. Use wait inside a while loop that rechecks the condition (producer-consumer).

Deadlock: two threads each hold one lock and wait for the other's (thread 1 holds A wants B, thread 2 holds B wants A). They stay BLOCKED forever. Prevent it by acquiring locks in a fixed global order, using tryLock with timeouts, or avoiding nested locks.

Exam pitfall: volatile does not make i++ atomic; synchronized also gives visibility.

Try two questions

Question 1 · Tier 2, Understand

What does volatile guarantee?

  1. Mutual exclusion
  2. That a variable is never cached by the compiler
  3. Visibility of writes across threads, but not atomicity
  4. Atomicity of ++ operations
Show the answer

C. A stop flag works with volatile; a counter does not.

Question 2 · Tier 1, Recall

Which keyword gives a method mutual exclusion on the object's monitor?

  1. volatile
  2. synchronized
  3. transient
  4. final
Show the answer

B. With synchronized inc(), 4 threads x 50,000 increments always give 200000.