synchronized
The Java keyword that lets only one thread at a time run a block of code guarded by the same lock object.
In more detail
A synchronized block protects an invariant that involves several reads and writes. Keep the guarded section small and give the lock a clear owner, because threads wait for each other there. The java.util.concurrent.locks package offers more flexible locks.
Example
synchronized (this) { balance = balance - amount; }Related terms
- critical section — The part of a program that reads and writes shared state and must therefore be run by only one thread at a time.
- race condition — A bug whose outcome depends on the timing of two things happening at once.
- atomic variable — A variable, such as AtomicInteger, whose updates like incrementAndGet happen as one indivisible step that no other thread can interrupt.
Taught in
- Concurrency Basics: Threads And Runnable — Modern Java: Virtual Threads & High-Throughput Services
- Inheritance, Overriding And Object's Methods — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Platform And Virtual Threads, Runnable And Callable — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Thread Safety: Locks And Atomics — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
- Concurrent Collections And Parallel Streams — Oracle Certified Professional: Java SE 21 Developer (1Z0-830) Exam Prep
References
- Java Tutorials: Intrinsic Locks and Synchronization
- Java Tutorials: Synchronized Methods
- Java Language Specification, chapter 17: Threads and Locks