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

Taught in

References

Certification courses