Advertisement
Guest User

Untitled

a guest
May 24th, 2015
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. 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.
  2. ```java
  3. public class Cas {
  4.  
  5. public int value;
  6.  
  7. public boolean compareAndSwap(int expectedValue, int newValue) {
  8. int oldValue = value;
  9. if( value == expectedValue) {
  10. value = newValue; return true
  11. }
  12. else {
  13. return false;
  14. }
  15. }
  16. }
  17. ```
  18. 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.
  19.  
  20. In Action:
  21.  
  22. This is like a race between threads. Think about the game shock. First player wins. The rest get shocked (lose the game)
  23.  
  24. For example.
  25.  
  26. 1.) Thread 1 wants to compareAndSwap (0, 1)
  27. 2.) Thread 1 gets True. CAS increments to 1
  28. 3.) Thread 2 wants to compareAndSwap (0, 1)
  29. 4.) Thread 2 gets False. CAS stays
  30. 5.) Thread 2 tries again with compareAndSwap(1,2)
  31. 6.) Thread 2 gets True. CAS increments to 2
  32.  
  33.  
  34.  
  35.  
  36. Shortcomings
  37. False Positives.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement