"Practical Java High Concurrency Programming 5" Lets ordinary variables also enjoy atomic manipulation

Source: Internet
Author: User
Tags cas volatile

"Practical Java High Concurrency Programming 1" Pointers in Java: unsafe class

"Practical Java High Concurrency Programming 2" lock-free object reference: Atomicreference

"Practical Java High Concurrency Programming 3" object reference with timestamp: atomicstampedreference

"Practical Java High Concurrency Programming 4" Array can also be unlocked: Atomicintegerarray

Sometimes, due to poor initial consideration, or later changes in demand, some common variables may also be wired to secure demand. If the changes are not very large, we can simply modify each of the programs to use or read this variable place. But obviously, this does not conform to an important principle in software design--open and close principle. That is, the system should be developed to increase the function, and the modification should be relatively conservative. And, if there is a lot more to this variable in the system, one modification is a chore (and many use scenarios may be just read-only, and the strong demand for wireless security is completely intact).

If you have this problem, there is no need to worry here, because there is a practical tool class atomicintegerfieldupdater in the atom bag. It allows you to get thread safety from the CAS operation without changing (or rarely changing) the original code, so you can modify very little code to secure the thread. Does that sound exciting to you?

Depending on the data type, there are 3 kinds of updater, namely Atomicintegerfieldupdater, Atomiclongfieldupdater and Atomicreferencefieldupdater. As the name implies, they can be modified for an int, a long, and a normal object on the line CAs.

Now consider such a scene. Suppose an election is to be held somewhere. Now, if the voter votes for a candidate, it will be recorded as 1, or 0. The final ballot is clearly a simple summation of all the data.

 Public classAtomicintegerfieldupdaterdemo { Public Static classcandidate{intID; volatile intscore; }     Public Final StaticAtomicintegerfieldupdater<candidate>Scoreupdater= Atomicintegerfieldupdater.newupdater (candidate.class, "Score"); //Check if updater is working correctly     Public StaticAtomicinteger allscore=NewAtomicinteger (0);  Public Static voidMain (string[] args)throwsinterruptedexception {FinalCandidate Stu=Newcandidate (); Thread[] t=Newthread[10000];  for(inti = 0; I < 10000; i++) {T[i]=NewThread () { Public voidrun () {if(Math.random () >0.4) {scoreupdater.incrementandget (STU);                    Allscore.incrementandget ();            }                }              };        T[i].start (); }           for(inti = 0; I < 10000; i++) {t[i].join ();} System.out.println ("Score=" +Stu.score); System.out.println ("Allscore=" +Allscore); }}

The code above simulates this counting scenario. The number of votes for the candidate is recorded in Candidate.score. Note that it is a normal volatile variable. Volatile variables are not thread-safe. Line 6th to 7th defines the Atomicintegerfieldupdater instance, which is used to write to the Candidate.score. And the subsequent allscore we used to check the correctness of atomicintegerfieldupdater. If Atomicintegerfieldupdater really guarantees thread safety, then eventually the values of Candidate.score and allscore must be equal. Otherwise, Atomicintegerfieldupdater does not ensure thread-safe writing at all. The 12th to 21st line simulates the counting process, assuming that about 60% of the people voted in favour and that the vote was random. Line 17th modifies the Candidate.score (which should be thread safe) using updater, and the 18th line uses the Atomicinteger count as the reference datum.

If you run this program, it is not difficult to find that the final candidate.score is always equal to Allscore. This shows that Atomicintegerfieldupdater is a good way to ensure candidate.score thread safety.

Although Atomicintegerfieldupdater is very useful, there are a few things to note:

First, updater can only modify variables within its visible range. Because updater uses reflection to get this variable. If the variable is not visible, an error occurs. For example, if score is declared private, it is not feasible.

Second, in order to ensure that the variable is read correctly, it must be of type volatile. If we do not declare this type in our original code, it is simply a matter of stating it, which will not cause any problems.

Thirdly, because CAS operations are assigned directly through offsets in an object instance, it does not support static fields (Unsafe. Objectfieldoffset () does not support static variables).

Well, by Atomicintegerfieldupdater, is it possible for us to be more free to thread-safely protect system-critical data?

From the "Practical Java High concurrency program design"

"Practical Java High Concurrency Programming 5" Lets ordinary variables also enjoy atomic manipulation

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.