java multithreading and volatile base ----- atomicinteger

volatile :

Ensure visibility, when a shared variable is volatile it will be modified to ensure that
the modified values are immediately updated to the main memory (physical memory) when there are other threads need to read,
reads the new value from memory but by synchronized with the lock can also be achieved
visibility at the same time it will ensure that there will only be one thread acquires the lock and then perform synchronization code
and before releasing the lock will be changes to the variable flush into the main memory

Ordering:

Program sequence rule
: within a thread, according to the order of the code book EDITORIAL operations take place in writing in advance of the operation behind the
lock rule:
a unLock first operation occurred after a lock face the same amount of lock operations
volatile variable rules:
for a variable write operations occur in the face after the first read this variable
transfer rule:
if a first operation occurred in the operation of B, and B and the operation occurred in the first operation C, the operation can be drawn a first occurred in the operation C

volatlie key semantic two layers:

1) to ensure that the different threads of this variable operating
visibility, that a thread modifies the value of a variable, this new value to other thread is immediately visible.

2) prohibition instruction reordering

volatile and synchronized use of the environment

synchronized keyword is to prevent multiple threads to execute a piece of code, it will very much influence the efficiency of program execution

, While the volatile keyword in some cases better performance than synchronized,

But be careful volatile keyword is no substitute for the synchronized keyword,

Because the volatile keyword can not guarantee atomic operations

. In general, the use of volatile must have the following two conditions:

1) a write operation is not dependent on the variable current value

2) The tag is not included in the invariant other variables having

In fact, these conditions indicate that the effective value independent of any state of the program can be written to these volatile variables, including the current status of variables.

atomicinteger :

Atomic operations class implements increment, decrement atomicity operation
in java i ++ is not an atomic operation because he represents three operating
1. Get the value of i
value plus one 2.i
3. i is updated value is written
using volatile can not guarantee atomicity, atomic class may be used
to ensure that their operation is atomic increment operation (CAS)

Published 68 original articles · won praise 3 · Views 5217

Guess you like

Origin blog.csdn.net/Hqxcsdn/article/details/88710967