Advertisement
Kostiggig

incAndIncrement() on my own

May 7th, 2023 (edited)
1,018
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. package multithreading.compare_and_swap.inc;
  2.  
  3. import multithreading.compare_and_swap.lock.CompareAndSwapLock;
  4. import org.checkerframework.checker.units.qual.A;
  5.  
  6. import java.util.Map;
  7. import java.util.Random;
  8. import java.util.concurrent.ConcurrentHashMap;
  9. import java.util.concurrent.atomic.AtomicInteger;
  10.  
  11. public class SharedResource {
  12.  
  13.     public final AtomicInteger counter = new AtomicInteger(0);
  14.     public final Map<String, Integer> fails = new ConcurrentHashMap<>();
  15.  
  16.     void inc() {
  17.         fails.put(Thread.currentThread().getName(), 0);
  18.         try {
  19.             Thread.sleep(new Random().nextInt(10) * 10 + 10);
  20.         } catch (InterruptedException e) {
  21.             throw new RuntimeException(e);
  22.         }
  23.         boolean isSuccessful = false;
  24.         while(!isSuccessful) {
  25.             int currValueInsideCounter = counter.get();
  26.             int newValueToSwap = currValueInsideCounter + 1;
  27.  
  28.             isSuccessful = counter.compareAndSet(currValueInsideCounter, newValueToSwap);
  29.             if(!isSuccessful) {
  30.                 fails.computeIfPresent(Thread.currentThread().getName(), (key, value) -> value + 1);
  31.             }
  32.         }
  33.     }
  34. }
  35.  
  36.  
  37. package multithreading.compare_and_swap.inc;
  38.  
  39.  
  40. import java.util.Set;
  41.  
  42. public class Client {
  43.  
  44.     public static void main(String[] args) throws InterruptedException {
  45.         SharedResource resource = new SharedResource();
  46.         for (int i = 0; i < 600_000; i++) {
  47.             new Thread(resource::inc).start();
  48.         }
  49.  
  50.         Thread.sleep(3000);
  51.         System.out.println(resource.counter);
  52.  
  53.         int countOfThreadsNeededAtLeast2Tries = 0;
  54.         Set<String> keys = resource.failsCounter.keySet();
  55.         for(String key: keys) {
  56.             if(resource.failsCounter.get(key) > 1) countOfThreadsNeededAtLeast2Tries++;
  57.         }
  58.         System.out.println("Count of threads needed at least 2 tries: " + countOfThreadsNeededAtLeast2Tries);
  59.     }
  60. }
  61.  
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement