fork(1) download
  1. import java.lang.invoke.MethodHandles;
  2. import java.lang.invoke.VarHandle;
  3.  
  4. class SimulateCAS {
  5. private volatile int count;
  6.  
  7. private static final VarHandle COUNT;
  8. static {
  9. try {
  10. COUNT = MethodHandles.lookup().findVarHandle(SimulateCAS.class, "count", int.class);
  11. throw new Error(e);
  12. }
  13. }
  14.  
  15. private int cas(int expectation, int newValue) {
  16. return (int) COUNT.compareAndExchange(this, expectation, newValue);
  17. }
  18.  
  19. void add10k() {
  20. int oldValue, newValue;
  21. do {
  22. oldValue = count;
  23. newValue = oldValue + 1; // ?
  24. } while (oldValue != cas(oldValue, newValue)); // ?
  25. }
  26.  
  27. public static void main(String[] args) throws InterruptedException {
  28. final SimulateCAS demo = new SimulateCAS();
  29. Thread t1 = new Thread(() -> {
  30. for (int i = 0; i < 10000; i++) {
  31. demo.add10k();
  32. }
  33. });
  34. Thread t2 = new Thread(() -> {
  35. for (int i = 0; i < 10000; i++) {
  36. demo.add10k();
  37. }
  38. });
  39.  
  40. t1.start();
  41. t2.start();
  42. t1.join();
  43. t2.join();
  44. System.out.println(demo.count);
  45. }
  46. }
Success #stdin #stdout 0.08s 33436KB
stdin
Standard input is empty
stdout
20000