Java Concurrent Programming 4_ thread synchronization volatile keyword

Source: Internet
Author: User
Tags volatile

Previous Blog post Java Concurrency programming 3_ thread synchronization synchronized keyword in Java to ensure that thread synchronization of the keyword synchronized, in fact, Java also has a weak synchronization mechanism volatile. The volatile keyword is a lightweight synchronization mechanism in Java that is used to synchronize update operations of variables to other threads. From the point of view of memory visibility, writing a volatile variable is equivalent to exiting a synchronous block of code, and reading a volatile variable is equivalent to entering a synchronous code block.

Old memory model: guaranteed read-write volatile occurs directly in the main memory.

The semantics of volatile are patched and enhanced under the new memory model (1.5): If thread A is written to the volatile variable V and thread B reads V, all variable values visible to a at V are now guaranteed to be visible to B.

sentence: volatile ensure visibility, but not atomicity.

Atomic: A set of statements is executed as an indivisible unit. Any thread that executes a synchronous block of code cannot see that another thread is executing a synchronous block of code that is protected by the same lock. The non-atomicity of volatile variables is most easily ignored.

Visibility: refers to a thread that modifies the value of a shared variable, and the other thread immediately learns about the change.

non-atomic nature of volatile

Variables defined as volatile do not guarantee that all operations are atomic, and because of their non-atomicity, volatile does not guarantee the security of multithreaded concurrency. As in the following code:

public class Test implements runnable{public volatile int race = 0; @Overridepublic void Run () {increase ();} private void Increase () {race + +;} public static void Main (string[] args) {Test t = new Test (); Thread [] Threads = new Thread[1000];for (int i = 0; i <; i++) {threads[i] = new Thread (t); Threads[i].start ();} while (Thread.activecount () > 1) {Thread.yield ();} Ensure that 1000 threads have been executed when printing System.out.println (T.race);}}

This code opens up 1000 threads and race the variable to the self-increment. Theoretically, the execution result should be 1000 if the thread is safe. But actually the result of execution is a value less than 1000.

Analyze the code in the above case, the problem is in the race++ code. It is not an atomic operation. This code is actually divided into three operations: read the value of the race, add 1 operations, write a new value.

It is clear that the definition of a variable as Vilatile does not guarantee atomicity:

Thread 1 reads the original value of the variable race first, then thread 1 is blocked, thread 2 also reads the original value of the variable race, then adds 1 operations, writes the value after +1 to the working memory, writes the main memory, and then the thread 1 then adds 1 operations, because the value of the race has been read, At this point in the working memory of thread 1, the value of race is still the previous value, so thread 1 adds 1 to race, and then writes the value to the working memory and finally to main memory. So there are two lines Cheng after the end of the fact only added once. The reason for this is that volatile is not a guarantee of atomicity.

You can change the self-increment action to a synchronized block of code to resolve.

Private synchronized void increase () {race + +;}
the visibility of volatile

A thread modifies the value of a volatile variable, and the new value is immediately visible to other threads.

Boolean ready;//thread 1while (!ready) {       dosomthing ();} Thread2ready = true;

This is a common method of destroying threads. However, the problem is that the ready variable is changed to true before it can be written to main memory, and then it goes to the other thread to execute, and then it enters the loop. At this time, the role of volatile is reflected. volatile The variable guarantees that he will be immediately known to other threads after modifying it within a thread.

Usage scenarios for Volatile variables this article is written in detail: Java theory and Practice: Correct use of Volatile variables

Java Concurrent Programming 4_ thread synchronization volatile keyword

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.