6 · Advanced · lesson 34 of 41
synchronized & Locks
Coordinating access so shared state stays consistent.
Java
class Counter {
private int n;
public synchronized void inc() { n++; }
public synchronized int get() { return n; }
}
// Explicit lock
ReentrantLock lock = new ReentrantLock();
lock.lock();
try { /* critical section */ } finally { lock.unlock(); }Loading 3D scene…
Key takeaways
- ✓synchronized guarantees mutual exclusion and visibility.
- ✓Prefer AtomicInteger / ConcurrentHashMap for simple cases.