SetState original method and effect analysis compareAndSetState

There are three AQS protected methods: getState, setState, compareAndSetState.

These three methods AQS is available in three basic tools to customize your synchronization method is to get the state of the state, then setState and compareAndSetState are used to modify the status of both what is the difference and why the two can coexist, its What are the respective usage scenario?

AQS ReentrantLock analysis and source code shows:

compareAndSetState typically used before acquiring the lock, while trying to lock on the state to be modified, under this scenario, because the current thread is not the holder of the lock, so changes to the state is not thread-safe, that there may be a plurality of threads attempt to modify the state, it is necessary to ensure that the atomic operation state changes, i.e., using a local class CAS unsafe method;
the setState method is commonly used currently holding a lock thread state variable changes, there is no competition is thread-safe, so here is no need to use CAS to ensure atomicity, modify the performance is more important.

Guess you like

Origin blog.csdn.net/ko0491/article/details/90768892