Multithreading Basic Concepts

Visibility, atomicity, and ordering in the Java memory model.

Visibility:
refers to the visibility between threads, the state modified by one thread is visible to another thread.
In Java, volatile, synchronized, and final implement visibility.


Atomicity:
Atom is the smallest unit in the world and is indivisible.
For example, a=0; (a non-long and double types) This operation is inseparable, then we say that this operation is an atomic operation. Another example: a++; This operation is actually a = a + 1; is divisible, so it is not an atomic operation. The classes of AtomicInteger, AtomicLong, and AtomicReference concurrent packages provide an atomic operation API.
Synchronized in Java and operations in lock and unlock guarantee atomicity.


Ordered:
The execution order of multiple threads is reordered. For example, the main thread defines 2 variables a=0, b=0; thread A will execute a=2, b=1; thread B will execute while(a=2){b=3}, which is possible b The value of thread a is undefined. The Java language provides two keywords, volatile and synchronized, to ensure the orderliness of operations between threads.

Common patterns for safe publishing:
Initialize an object reference in a static initializer Save the application of
the object to a volatile type field or an AtomicReferance object
Save the object reference to a final type field of a properly constructed object Save
the object reference into a domain protected by a lock.

Compared to volatile, reads and writes to final fields are more like ordinary variable accesses. For final fields, compilers and processors are subject to two reordering rules:
the writing of a final field within the constructor, and the subsequent assignment of a reference to the constructed object to a reference variable, between these two operations Reordering is not possible.
There is no reordering between an initial read of a reference to an object containing a final field and a subsequent initial read of the final field.

Similar to Volatile, but Final is mainly used for immutable variables (basic data types and non-basic data types) for safe release (initialization). While Volatile can be used to safely publish immutable variables, it can also provide visibility of mutable variables.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326565294&siteId=291194637
Recommended