(turn) using CAS algorithm to implement universal thread-safe State machine

Source: Internet
Author: User
Tags cas

In a multithreaded environment, if a class is stateful, we need to ensure that all instances of the class are in the same state before use, otherwise there will be a bug with no intention. The following is the implementation of the universal thread-safe state machine.

PublicClass threadsavestate{Privateint x;Privateint y;PrivateEnum State {NEW, INITIALIZING, INITIALIZED};Private final atomicreference<state> init =New Atomicreference<state> (state.new);PublicThreadsavestate () {};PublicThreadsavestate (int x,int y) {initialize (x, y);}PrivatevoidInitializeint x,int y) {if (!init.compareandset (State.new, state.initializing)) {ThrowNew IllegalStateException ("Already initialized"); }this.x = x;This.y = y;... Do anything else the original constructor did Init.set (state.initialized);} //all public interfaces, first call this method to detect object integrity private void checkinit () {if (Init.get ()! = state.initialized) {throw new IllegalStateException ( "uninitialized");}} //sample Common Interface public int getx () {checkinit (); return x;} //sample Common Interface public int gety () {checkinit (); return y;}            

This mode uses the Compareandset method to manipulate the atomic reference of an enumeration, about the Compareandset method, which is the CAS algorithm, namely: Compare and swap, translated into comparison and exchange, the source code is as follows:

With CAs, the Java.util.concurrent package provides an optimistic lock that differs from the Synchronouse sync Lock, and uses these classes to perform better on a multi-core CPU machine.

Combined with the Compareandset source we look at:

/** * Atomically     Sets the value to the given updated value * If the current value {@code = =} The expected value.  * @param expect the expected value * @param update the new Value * @return True if successful.     False return indicates that * the actual value is not equal to the expected value. */public final boolean compareandset (v expect, v update) {return unsafe.compareandswapobject (this, Valueoffset, expect, update);}         

According to the note, the CAS has 3 operands, the memory value V, the old expected value A, and the new value B to be modified. If and only if the expected value A and the memory value of V are the same, the memory value V is modified to B, which returns true, otherwise false is returned.

And look at the code we initialized:

if (!init.compareAndSet(State.NEW, State.INITIALIZING)) {            throw new IllegalStateException("Already initialized");        }

Initialization is initiated only if state is new, or the error is directly. This guarantees the integrity of the object, because if there is no such defense mechanism, in case one thread wants to invoke initialize () on an instance and another thread attempts to use the instance, the second thread may see the instance in an inconsistent state.

Reprint: http://blog.csdn.net/qq_27258799

(turn) using CAS algorithm to implement universal thread-safe State machine

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.