Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- The CAS will compare the object in memory with the old value. If equal then the new value is put into its place and the method returns true. Otherwise false is returned.
- ```java
- public class Cas {
- public int value;
- public boolean compareAndSwap(int expectedValue, int newValue) {
- int oldValue = value;
- if( value == expectedValue) {
- value = newValue; return true
- }
- else {
- return false;
- }
- }
- }
- ```
- The compareAndSwap method will compare the object in question and if the expectedValue is the same as the object, then the new value will replace the object in question.
- In Action:
- This is like a race between threads. Think about the game shock. First player wins. The rest get shocked (lose the game)
- For example.
- 1.) Thread 1 wants to compareAndSwap (0, 1)
- 2.) Thread 1 gets True. CAS increments to 1
- 3.) Thread 2 wants to compareAndSwap (0, 1)
- 4.) Thread 2 gets False. CAS stays
- 5.) Thread 2 tries again with compareAndSwap(1,2)
- 6.) Thread 2 gets True. CAS increments to 2
- Shortcomings
- False Positives.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement