Java Concurrency--volatile

Source: Internet
Author: User
Tags volatile

Learn the principle of computer composition must know, in order to solve the problem of memory speed and CPU speed, in the CPU design to add a caching mechanism, the cache speed between the CPU and main memory. At the time of the operation, the CPU maps the data needed in the cache, then directly operates the data in the cache, and then writes the cached data back to main memory. This is not a problem in a single-threaded environment. But it's a big difference in a multithreaded environment.
Suppose there is a scenario like this: There are two threads thread1 and thread2, and they all operate on a data int a=2 that is located on main memory (the operation is to read the value of a and perform a self-increment operation). Logically correct result: should be the last a=4. However, it is possible that THREAD1 will a=2 from main memory to its own working memory, since the increment into A=3, before the a=3 from the working memory to write back to main storage, THREAD2 will be a=2 from the main memories from the main memory mapped to their own work, but also since the increase into a=3. The two threads then write a=3 back to main memory. Obviously, a=3 is not what we want to see. Look, this is a common cache consistency issue. Two threads to A's operation results are not visible, thread1 do not know thread2 to a self-increment, thread2 also do not know thread1 to a self-increment. In multithreaded programming there is the problem of consistency. (in JMM, it can be known that memory is divided into primary memory and working memory, each thread has its own working memory and they share the main memory)。
So we're going to get the threads to be able to see each other's operations on shared variables, and the volatile keyword in the Java language does one thing. Using a volatile modified shared variable, when the thread thread modifies his value, he immediately forces the modified value to be written back to main memory and notifies other threads that are using the shared variable: The value of the variable in their cache has been invalidated. Please re-read from main memory.
read the volatile dry matter carefully, a total of 3 points affect:
1 forcing a modified value to be flushed to main memory
2 notification that other related thread variables have been invalidated
3 Other threads will re-read from main memory when they use the variable again
 
This solves the problem of visibility in Java concurrency programming.
Visibility: When multiple threads access the same shared variable, a thread's modification of that shared variable can be known in real time by other threads accessing the shared variable.
To continue with the example above, if variable A is using the volatile modifier, then in Thread1, when a becomes 3, it is forced to flush to main memory. If this time, Thread2 has mapped the a=2 from main memory to the cache, then before the a self-increment operation, it will re-read the a=3 in main memory, then increment to a=4, and then write back to main memory. The process is perfect, but does this guarantee a final result must be 4? Not necessarily.
To continue with the example above, if variable A is using the volatile modifier, then in Thread1, when a becomes 3, it is forced to flush to main memory. If this time, Thread2 has mapped a=2 from main memory to the cache and has done the self-increment operation, at this time a=3, then the value of a in the final main memory is 3.
So, if we want the final value of a to be 4, just to ensure that visibility is not enough, but also to ensure atomicity. That is, the self-increment operation of variable a lock, to ensure that at any one time only one thread to a self-increment operation. It can be said that volatile is a "lightweight lock", which guarantees the visibility of the lock, but does not guarantee the atomic nature of the lock.
A typical use of volatile variables is the use of tokens for those states, such as:

Java code
    1. Volatile Boolean flag=false;
    2. while (!flag) {
    3. DoSomething ();
    4. }


In other threads, the value of flag may be modified to true, which represents the exit loop. If you do not use the volatile flag, the main thread may not have received a message whose value has changed after flag has been reclaimed. This is a typical application of volatile. Of course, we can also cache the most recent content using volatile types of immutable objects. For the example of the previous blog http://yizhenn.iteye.com/blog/2286623: The servlet class that returns the corresponding uppercase characters according to the 1-9 Arabic numerals of a request.

Java code
  1. Public class onevaluecache{
  2. Private final Integer lastnum;
  3. Private final String laststr;
  4. Public Onevaluecache (Integer num,string str) {
  5. this.lastnum=new Integer (num);
  6. this.laststr=new String (str);
  7. }
  8. Public String getlaststr (int num) {
  9. if (num==null | |!num.equles (LASTSTR))
  10. return null;
  11. Else
  12. return new String (LASTSTR);
  13. }
  14. }



Java code
    1. @ThreadSafe
    2. Public class Myservlet implements Servlet
    3. {
    4. Private volatile Onevaluecache cache=new Onevaluecache (null,null);
    5. Public Void Service (ServletRequest req,servletresponse res) {
    6. int I=getnum (req);
    7. String str=cache.getlaststr (i);
    8. if (str==null) {
    9. Str=gethanzibynum (i)
    10. cache=New Onevaluecache (I,STR);
    11. }
    12. Responsehanzi (RES,STR);
    13. }
    14. }

Java Concurrency--volatile

Related Article

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.