Java volatile keywords
In Java thread concurrency processing, there is a great deal of confusion about the use of a keyword volatile, thinking that by using this keyword, you can do everything in parallel with multithreading.
The Java language supports multithreading, in order to solve the problem of thread concurrency, the synchronization block and volatile keyword mechanism are introduced into the language.
Synchronized
Synchronized block Everyone is more familiar with the Synchronized keyword to achieve, all add synchronized and block statements, in multi-threaded access, at the same time only one thread can use
Synchronized a modified method or block of code.
Volatile
A variable decorated with volatile, the thread reads the variable's most-modified value each time it uses the variable. Volatile are easily misused for atomic manipulation.
Here's an example where we implement a counter that invokes the Counter Inc method each time the thread starts, adding a
Execution Environment--JDK version: jdk1.6.0_31, Memory: 3G cpu:x86 2.4G
public class Counter
{public
static int count
= 0;
public static Void Inc ()
{
//is delayed 1 milliseconds, resulting in a significant
try {
thread.sleep (1);
}
catch (Interruptedexception
e) {
}
count++;
}
public static void Main (string[]
args) {
//start 1000 threads at the same time to perform i++ calculations to see the actual result for
(int i
= 0;
i < 1000;
i++) {
new Thread (New Runnable ()
{
@Override public
Void Run ()
{
counter.inc ();
}
}). Start ();
}
Each running value may be different, possibly 1000
System.out.println ("Run Result: counter.count=" +
counter.count);
}
运行结果:Counter.count=995
实际运算结果每次可能都不一样,本机的结果为:运行结果:Counter.count=995,可以看出,在多线程的环境下,Counter.count并没有期望结果是1000
很多人以为,这个是多线程并发问题,只需要在变量count之前加上volatile就可以避免这个问题,那我们在修改代码看看,看看结果是不是符合我们的期望
public class Counter
{public
volatile static int count
= 0;
public static Void Inc ()
{
//is delayed 1 milliseconds, resulting in a significant
try {
thread.sleep (1);
}
catch (Interruptedexception
e) {
}
count++;
}
public static void Main (string[]
args) {
//start 1000 threads at the same time to perform i++ calculations to see the actual result for
(int i
= 0;
i < 1000;
i++) {
new Thread (New Runnable ()
{
@Override public
Void Run ()
{
counter.inc ();
}
}). Start ();
}
Each running value may be different, possibly 1000
System.out.println ("Run Result: counter.count=" +
counter.count);
}
Run Result: counter.count=992
The results of the operation is still not 1000 of our expectations, the following we analyze the reasons
In the context of Java garbage collection, the allocation of memory at the time of the JVM runtime is described. One of the memory areas is the JVM virtual machine stack, where each thread runs with a line stacks,
Line stacks saves the thread run-time variable value information. When a thread accesses a value of an object, the value of the variable corresponding to the heap memory is first found by reference to the object, and then the heap memory
The value of the variable is load into thread local memory, a copy of the variable is established, and then the thread no longer has anything to do with the object in the heap memory variable value, but instead directly modifies the value of the replica variable.
At some point after the modification (before the thread exits), the value of the thread variable copy is automatically written back to the object's variable in the heap. This makes the value of the object in the heap change. A picture below
Describe this write interaction
Read and load Copy variables from main memory to current working memory
Use and assign execute code to change shared variable values
Store and write use working memory data to refresh main memory related content
Where use and assign can occur multiple times
But these operations are not atomic, that is, after read load, if the main memory count variable has been modified, the value in the thread's working memory will not produce a corresponding change because it has been loaded, so the calculated result is not the same as expected
For volatile-decorated variables, the JVM virtual machine only guarantees that the values loaded from main memory to the working memory of the thread are up to date
For example, if thread 1, thread 2, finds that the value of count in main memory is 5 in the read,load operation, the newest value is loaded
After the thread 1 heap count is modified, it is write into main memory, and the count variable in main memory becomes 6
Thread 2 because the read,load operation has already been performed, the variable value of the main memory count is also updated after the operation is 6
When two threads are modified with the volatile keyword in a timely manner, concurrency is still present.
Thank you for reading, I hope to help you, thank you for your support for this site!