synchronized, volatile and Race Conditions
45 min · Advanced
A race condition happens when two threads use shared data at the same time and the result depends on who runs first. synchronized, volatile and the atomic classes are Java's tools against it, and "synchronized vs volatile" is one of the most asked concurrency questions. Section 10 (Race Conditions & synchronized, Visibility & volatile, Locks & Atomic Variables) taught them; this lesson is the revision.
Topics in this lesson
- Race condition: counter++ is not atomic
- synchronized: methods vs blocks, object lock vs class lock
- volatile: visibility, not atomicity
- AtomicInteger and compare-and-set
- wait/notify and the producer-consumer question
Interview questions this lesson answers
- What is a race condition?
- What is a critical section?
- Why is count++ not thread-safe?
- What does the synchronized keyword do?
- What is the difference between a synchronized method and a synchronized block?
- What is the difference between an object lock and a class lock?
- Can two threads run two different synchronized methods of the same object at once?
- Can a non-synchronized method run while another thread is inside a synchronized method of the same object?
- Is synchronized reentrant?
- What happens to the lock if an exception is thrown inside synchronized code?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.