Title: Synchronization and concurrency
Course: CPS 189: Java Certification - Review, Practice & Prepare (Development) > Section: (OLDstyle) Learning Modules

Synchronization and concurrency

- Threads may share the data stored in objects.  They may independently update those data.  This introduces data inconsistency errors that are addressed by thread synchronization or concurrency.
- Thread interference happens when two threads interleave while acting on the same data.  If both threads are updating the data, it becomes very likely that one thread will not be updating the latest version of the data, or that one thread’s update will be lost.
- There are two ways to implement thread synchronization:
  - At the method level, declare the method with the synchronized modifier.  This prevents thread interleaving by only allowing one thread at a time to execute the method.
  - At the statement level, prefix it with synchronized(this).  This prevents thread interleaving by only allowing one thread at a time to execute the statement.

- An atomic operation is a set of multiple operations performed as a synchronized unit.
- An atomic variable is one in which only atomic operations may be performed.
- Thread synchronization may also be accomplished with atomic variables.
- The java.util.concurrent.atomic package enables atomic variables.

For more information, see:
Synchronization
Thread Interference
Synchronized Methods
Intrinsic Locks and Synchronization
Atomic Variables
CPS 261, Unit 7