Java Concurrency Programming-volatile keywords

Source: Internet
Author: User

The Java language provides a slightly weaker synchronization mechanism, the volatile variable, that is used to ensure that the update operation of the variable is notified to other threads.

When a variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared, so the action on that variable is not reordered with other memory operations, and the volatile variable is not cached in registers or where the processor is not visible. Therefore, the most recent write value is always returned when the volatile variable is read. Accessing a volatile variable does not perform a lock operation, so it does not cause the execution thread to block, so the volatile variable is a more lightweight synchronization mechanism than the Sychronized keyword.

A typical usage of a volatile variable: check a status token to determine whether to exit the loop

volatileboolean asleep;while( ! asleep)       countSomeSheep();

Volatile variables are usually identified with an operation complete, an interrupt, or a status. Although volatile variables can be used to represent other state information, use caution when using them. For example, the semantics of volatile are not sufficient to guarantee the atomicity of the increment operation (count++) unless you can ensure that only one thread writes to the variable.

The locking mechanism can guarantee both visibility and atomicity, while volatile variables can only guarantee visibility.

Some conditions that should be met by using volatile

    • The write operation on a variable does not depend on the current value of the variable, or you can ensure that only a single thread updates the value of the variable
    • The variable is not included in the invariant condition with other state variables
    • The access variable is not required to lock


Like and understand the above three, first look at the first article

The write operation on a variable does not depend on the current value of the variable, or you can ensure that only a single thread updates the value of the variable

Common operations such as: i++ operation, I write needs to rely on the value of I itself, when there are multiple threads simultaneously executing i++, a, b read the value of I, and then do the + + operation, the actual value may be only one + +

The following code:

 Public  class volatiletest extends Thread {        Static volatile intA=0; Public void Run()      { for(inti =0; I <Ten; i + +)Try{a = a +1; Sleep -); }Catch(Exception e) {              }       } Public Static void Main(String []args)throwsinterruptedexception {Thread thread[]=Newthread[ -]; for(intI=0;i< -; i++) thread[i]=NewVolatiletest (); for(intI=0;i< -; i++) Thread[i].start (); for(intI=0;i< -; i++) Thread[i].join (); System. Out.println ("A:"+A); }}

Run, you can tell the result of a is not necessarily equal to 1000, many times less than 1000


Article two: The variable is not included in the invariant condition with other state variables

See an example: a range value lower is always less than or equal to upper this is an invariant

   Public  class numberrange{           Private volatile intLower, Upper; Public int Getlower(){returnLower; } Public int Getupper(){returnUpper; } Public void Setlower(intValue) {if(Value > Upper)Throw NewIllegalArgumentException (...);           lower = value; } Public void Setupper(intValue) {if(Value < lower)Throw NewIllegalArgumentException (...);           upper = value; }       }

This approach restricts the state variables of the scope, so defining the lower and upper fields as volatile types does not fully implement the thread safety of the class, so synchronization is still required. Otherwise, if it happens that two threads execute Setlower and setupper at the same time using inconsistent values, the scope will be in an inconsistent state. For example, if the initial state is (0,5), at the same time, thread A calls Setlower⑷ because it is using a volatile variable, then the read upper is 5, and thread B calls Setupper⑶ the same. Because of the volatile variable, the read lower is 0, it is obvious that the two operations cross-deposit value is not eligible, then two threads will be used to protect the invariant type of check, so that the final range value is (4,3)-An invalid value. As for the other operations on the scope, we need to atomically setlower () and Setupper () operations--and it is not possible to define a field as a volatile type.


Article three: From the front can be known-locking mechanism can ensure both visibility and atomicity, and volatile variables can only guarantee visibility.

So the volatile variable does not guarantee the atomicity of the lock operation.

Java Concurrency Programming-volatile keywords

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.