[Practical Java high concurrency Program Design 5] let common variables also enjoy atomic operations, java program design

Source: Internet
Author: User

[Practical Java high concurrency Program Design 5] let common variables also enjoy atomic operations, java program design

[Practice: Java high concurrency Program Design 1] pointer in Java: Unsafe class

[Java high concurrency program design 2] Lock-free Object Reference: AtomicReference

[Practical Java high concurrency Program Design 3] References to objects with timestamps: AtomicStampedReference

[Practical Java high concurrency Program Design 4] Arrays can also be unlocked: AtomicIntegerArray

 

Sometimes, some common variables may also have thread security requirements due to low-week initial considerations or later demand changes. If there is not much change, we can simply modify every place in the program that uses or reads this variable. But obviously, this is not in line with an important principle in software design-the open and closed principle. That is to say, the system should develop the function, and the modification should be relatively conservative. In addition, if many variables are used in the system, one modification is also annoying (in many use cases, it may be read-only, and strong requirements for wireless security, can be kept as is ).

If you have such troubles, you don't need to worry about it here, because there is also a practical tool class AtomicIntegerFieldUpdater in the atomic bag. It allows you to keep the original code unchanged (or rarely changed), so that common variables can also enjoy the thread security brought about by the CAS operation, so that you can modify very little code, to guarantee thread security. Does that sound exciting?

Depending on the data type, there are three types of Updater: AtomicIntegerFieldUpdater, AtomicLongFieldUpdater, and AtomicReferenceFieldUpdater. As the name suggests, they can modify CAS for int, long, and common objects respectively.

Now let's think about this scenario. Assume that an election is required in a certain place. Now we simulate this ticket scenario. If the voter votes for a candidate, the ticket is counted as 1; otherwise, the ticket is counted as 0. The final vote is clearly a simple sum of all data.

Public class AtomicIntegerFieldUpdaterDemo {public static class Candidate {int id; volatile int score;} public final static AtomicIntegerFieldUpdater <Candidate> scoreUpdater = AtomicIntegerFieldUpdater. newUpdater (Candidate. class, "score"); // check whether the Updater is working correctly. public static AtomicInteger allScore = new AtomicInteger (0); public static void main (String [] args) throws InterruptedException {final Candidate stu = new Candidate (); Thread [] t = new Thread [10000]; for (int I = 0; I <10000; I ++) {t [I] = new Thread () {public void run () {if (Math. random () & gt; 0.4) {scoreUpdater. incrementAndGet (stu); allScore. incrementAndGet () ;}}; t [I]. start () ;}for (int I = 0; I <10000; I ++) {t [I]. join ();} System. out. println ("score =" + stu. score); System. out. println ("allScore =" + allScore );}}

 

The above code simulates this ticketing scenario. The number of votes received by the Candidate is recorded in Candidate. score. Note that it is a common volatile variable. The volatile variable is not thread-safe. 6th ~ Row 7 defines the AtomicIntegerFieldUpdater instance, which is used to write Candidate. score. The subsequent allScore is used to check the correctness of AtomicIntegerFieldUpdater. If AtomicIntegerFieldUpdater ensures thread security, the final Candidate. score and allScore values must be equal. Otherwise, it indicates that AtomicIntegerFieldUpdater does not ensure thread-safe writing. 12th ~ Line 21 simulates the vote counting process. Here we assume that about 60% of people vote in favor and the vote is random. Row 17th uses Updater to modify Candidate. score (thread-safe here), and row 18th uses AtomicInteger as the reference.

If you run this program, it is not difficult to find that the final Candidate. score is always equal to allScore. This indicates that AtomicIntegerFieldUpdater ensures the thread security of Candidate. score.

Although AtomicIntegerFieldUpdater is easy to use, there are several precautions:

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

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

Third, since CAS operations directly assign values through the offset in the object instance, it does not support static fields (Unsafe. objectFieldOffset () does not support static variables ).

Okay. Does AtomicIntegerFieldUpdater allow us to implement thread-safe protection for key system data as we like?

 

From "Practical Java high concurrency Program Design"

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.