Atomic variables (Atomiclong, Atomicinteger, atomicreference)

Source: Internet
Author: User
Tags gety

J2SE 5.0 provides a set of atomic class to help us simplify synchronization. The basic principle is to use the synchronous synchronized method to achieve a long, integer, object increment, subtraction, assignment (update) operation. For example, the + + operator Atomicinteger can atomic the integer it holds. The program code that requires access to two or more atomic variables (or two or more operations for a single atomic variable) usually needs to be synchronize so that both operations can be treated as a atomic unit.

For the array atomic variable, only one index variable can be changed at a time, and there is no function to make atomic changes to the entire array.

Several methods of atomic
Getandset (): Sets the new value and returns the old value.
Compareandset (Expectedvalue, NewValue): If the current value is equal to the expected value (Expectedvalue), the specified value is updated with the new value (NewValue), and if the update succeeds, Returns TRUE, otherwise returns false, in other words: Set the atomic variable to a new value, but if the variable I saw last time has been modified by another thread (which does not match the value I expected to see), then the update failed

An example of atomicreference from effective Java (2):
Java code

 public class Atomictest {private int x, y; private enum State {NEW, initializing, initialized}; private Final Ato micreference<state> init = new atomicreference<state> (state.new); Public atomictest () {} public atomictest (int x, int y) {initialize (x, y);} private void Initialize (int x, int y) {if ( !init.compareandset (State.new, state.initializing)) {throw NEW illegalstateexception ("Initialize is Error");} this.x = X This.y = y; Init.set (state.initialized); public int GetX () {checkinit (), return x;} public int GetY () {checkinit (), return y;} private void Checkinit () {if (Init.get () = = state.initialized) {throw new IllegalStateException ("uninitialized");} } public class Atomictest {private int x, y; private enum State {NEW, initializing, initialized}; private Final Atomi creference<state> init = new atomicreference<state> (state.new); Public atomictest () {} public atomictest (int x, int y) {initialize (x, y);} private void Initialize (int x, int y) {if (!init.compareandset (State.new, state.initializing)) {throw NEW illegalstateexception ("Initialize is Erro R "); } this.x = x; This.y = y; Init.set (state.initialized); public int GetX () {checkinit (), return x;} public int GetY () {checkinit (), return y;} private void Checkinit () {if (Init.get () = = state.initialized) {throw new IllegalStateException ("uninitialized");} } }

The above example is easier to understand, but it seems to be of little value, and in practical applications, we generally use the atomic class in the following ways:
Java code
public class Countertest {Atomicinteger counter = new Atomicinteger (0), public int count () {int: boolean flag; do {result = Counter.get ();////single thread, Compareandset return is always true,//multithreading, counter may be set by other threads when compare, the new value is required The new one again to compare,//If you still do not get the latest value, then continue to loop until you get the latest value flag = Counter.compareandset (result, result + 1); while (!flag); return result; public static void Main (string[] args) {final countertest c = new Countertest (), new Thread () {@Override public void R Un () {c.count ();}}. Start (); New Thread () {@Override public void run () {C.count ();}}. Start (); New Thread () {@Override public void run () {C.count ();}}. Start (); The public class Countertest {Atomicinteger counter = new Atomicinteger (0), public int count () {int result; Boolean flag ; do {result = Counter.get ();//breakpoint//single thread, Compareandset return is always true,//multithreading, counter may be set by other threads when compare, the new value is required To go over it again,///If you still don't get the latest value, keep looping until you get the latest value flag = Counter.compareandset (result, ResUlt + 1); while (!flag); return result; public static void Main (string[] args) {final countertest c = new Countertest (), new Thread () {@Override public void R Un () {c.count ();}}. Start (); New Thread () {@Override public void run () {C.count ();}}. Start (); New Thread () {@Override public void run () {C.count ();}}. Start (); }} A "read-Modify-write" composite operation like i++ (in a sequence of actions, the latter operation is dependent on the results of the previous operation, and there is a problem when multithreading is concurrent, because one thread may have modified the variable, and another thread has not detected such a change, and after using the atomic variable, You can avoid this problem by merging a series of composite operations into an atomic operation, I++=>i.incrementandget ()
Atomic variables can only guarantee that the operation of a variable is atomic, if there are multiple atomic variables are dependent on the composite operation, it can not be safe, the other is to add more complex operations as an atomic operation, you need to use the synchronized will be used as an atomic operation of the statement surrounded. Because a variable share variable (class instance member variable) is involved in synchronization, it is not necessary to use the synchronized

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.