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

Source: Internet
Author: User

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

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

Atomicreference cannot solve the problem above all because the object is missing state information during the modification process. The object value itself is drawn with the state as an equal. Therefore, as long as we can record the state value of the object during the modification process, we can solve the problem that the object is repeatedly modified, which causes the thread not to correctly judge the state of the object.

That's exactly what Atomicstampedreference did. Not only does it maintain the object value internally, it also maintains a timestamp (I call it a timestamp here, in fact it can make any integer that uses an integer to represent the state value). When the corresponding value of atomicstampedreference is modified, the timestamp must be updated in addition to updating the data itself. When atomicstampedreference sets the value of an object, both the object value and the timestamp must meet expectations for the write to succeed. Therefore, even if the object value is read and written repeatedly, writing back the original value, as long as the timestamp changes, can prevent inappropriate writing.

Several of Atomicstampedreference's APIs have added information about timestamps based on Atomicreference:

//Compare setting parameters in order: Expected values write new value expected timestamp new timestamp Public BooleanCompareandset (V expectedreference,v newreference,intExpectedstamp,intNewstamp)//get current object reference PublicV getreference ()//Get current timestamp Public intGetstamp ()//set current object reference and timestamp Public voidSet (V newreference,intNewstamp)

With Atomicstampedreference This magic weapon, we will never have to worry about the object is written bad! Now, let's use atomicstampedreference to fix that VIP card recharge question:

01 Public classAtomicstampedreferencedemo {02StaticAtomicstampedreference<integer> money=NewAtomicstampedreference<integer> (19,0);03 Publicstaticvoid Main (string[] args) {04//simulate multiple threads updating the background database at the same time to recharge the user05 for(inti = 0; I < 3; i++) {06Final inttimestamp=Money.getstamp ();07Newthread () {08 Public voidrun () {09 while(true){10 while(true){integerm=money.getreference ();12if(m<20){13if(Money.compareandset (m,m+20,timestamp,timestamp+1)){System.out.println ("Balance less than 20 yuan, top up success, Balance:" +money.getreference () + "Yuan");15 Break;16                                 }17}Else{18//System.out.println ("Balance of more than 20 yuan, no need to recharge");19 Break ;20                             }21st                        }22                    }23                } 24}.start ();25         }26 27//user consumption thread, simulating consumption behavior28NewThread () {29publicvoid Run () {30 for(inti=0;i<100;i++){31 while(true){32inttimestamp=Money.getstamp ();M= Integermoney.getreference ();34if(m>10){System.out.println ("More than 10 yuan");36if(Money.compareandset (M, m-10,timestamp,timestamp+1)){PNS System.out.println ("$ 10 success, Balance:" +money.getreference ());38 Break;39                             }40}Else{System.out.println ("Not Enough money");42 Break;43                        }44                    }45Try{thread.sleep (100);}Catch(Interruptedexception e) {}46                 }47             } 48}.start (); 49    }50}
Line 2nd, we use Atomicstampedreference instead of the original atomicreference. The time stamp of the account is obtained on line 6th. Subsequent gifting operations are based on this timestamp. If the gift succeeds (13 rows), the timestamp is modified. Make it impossible for the system to give two times. Consumer threads are similar, with each operation making the timestamp add 1 (36 rows), making it impossible to repeat.

Executing the above code, you can get the following output:

Balance of less than 20 yuan, top-up success, balance: 39 yuan more than 10 yuan successful consumption of 10 yuan, balance: 29 More than 10 yuan successful consumption of 10 yuan, balance: 19 is more than 10 yuan successful consumption of 10 yuan, balance: 9 There is not enough money to see, the account was only given once.

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

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

Excerpt from: Practical Java High concurrency program design

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

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.