Java Concurrency - Synchronization (Thread Safety)

> Procedural Languages > Java > Java - Concurrency (Parallel Work)

1 - About

Concurrency - Synchronization in java.

If an object is visible to more than one thread, all reads or writes to that object's variables must be done through synchronized code

An important exception: final fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed.

This strategy is effective, but can present problems with liveness.

Synchronization is implemented by an internal entity known as the intrinsic lock or monitor lock.

  • Each object in Java is associated with a monitor, which a thread can lock or unlock.
  • Only one thread at a time may hold a lock on a monitor.
  • Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor.

Synchronization has two aspects:

The Java programming language neither prevents nor requires detection of deadlock conditions.



3 - Code

To create synchronized code (ie which gives consistent values) between threads, you use the synchronized word..

3.1 - Method

3.2 - Statement

4 - Documentation / Reference