- Java Storage
- Data Atomicity
- Change Visibility
- Execution Ordering
- Volatile Class Fields
- The JVM has a single global storage for storing data.
- Each thread maintains a local copy of data from global storage.
- Multiple threads introduce data-consistency problems.
- Each thread changes its own local copies of data.
- Each thread has a different view of the same data.
- The global storage data may differ from all thread views.
- The Java Memory Model defines properties to provide data consistency.
- The properties involve data atomicity, change visibility, and execution
order.
- These are the weakest properties; stronger implementations are allowed.
- They are also incorrect and are being revised.
- Read-write atomicity.
- All bits in a datum belong to the same value.
- All basic types except
long
and double
are read-write atomic.
- Object references included.
-
long
and double
need not be read-write atomic.
-
volatile
long
s and double
s are read-write atomic.
- Classes and their instances are not usually atomic.
- When can a thread-local change be seen by other threads?
- Releasing an object lock flushes the thread's changes back to global
storage.
- Acquiring an object lock loads the object data into the thread.
- Notice the two-step process: writer unlocks and reader locks.
-
synchronize
also indicates low-level storage updates.
- It is unclear if flushing and loading are atomic.
- Volatile fields are read from and written to global storage.
- First time reads always return a valid value.
- Either the initial value or some written value.
- Thread termination flushes local changes to global storage.
- It may take arbitrary long for changes to reach global storage.
- Within a thread, instructions are executed in sequential order.
- "As-if" sequential order, in the absence of side-effects.
- Optimizing re-arrangements.
- One thread may observe arbitray execution orders in an other thread.
- The sequence of synchronized and volatile references is preserved.
- Within-thread order is useless when interference is present.
- Multiple threads lead to data-consistency problems.
- Copies of data being changed.
- Java specifies weak data-consistency support.
- Although JVM implementations are usually stronger than specified.
-
long
and double
may not be atomic; other base types are.
- Classes as a whole are default non-atomic (unsynchronized).
- Volatile data types and class fields support atomic access.
- Usually exploited in special cases.
- Any significant sharing among threads requires synchronization.
- Beware unsyncnronized threads; interference is the rule.
This page last modified on 8 August 2002.