Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package multithreading.compare_and_swap.inc;
- import multithreading.compare_and_swap.lock.CompareAndSwapLock;
- import org.checkerframework.checker.units.qual.A;
- import java.util.Map;
- import java.util.Random;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.atomic.AtomicInteger;
- public class SharedResource {
- public final AtomicInteger counter = new AtomicInteger(0);
- public final Map<String, Integer> fails = new ConcurrentHashMap<>();
- void inc() {
- fails.put(Thread.currentThread().getName(), 0);
- try {
- Thread.sleep(new Random().nextInt(10) * 10 + 10);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- boolean isSuccessful = false;
- while(!isSuccessful) {
- int currValueInsideCounter = counter.get();
- int newValueToSwap = currValueInsideCounter + 1;
- isSuccessful = counter.compareAndSet(currValueInsideCounter, newValueToSwap);
- if(!isSuccessful) {
- fails.computeIfPresent(Thread.currentThread().getName(), (key, value) -> value + 1);
- }
- }
- }
- }
- package multithreading.compare_and_swap.inc;
- import java.util.Set;
- public class Client {
- public static void main(String[] args) throws InterruptedException {
- SharedResource resource = new SharedResource();
- for (int i = 0; i < 600_000; i++) {
- new Thread(resource::inc).start();
- }
- Thread.sleep(3000);
- System.out.println(resource.counter);
- int countOfThreadsNeededAtLeast2Tries = 0;
- Set<String> keys = resource.failsCounter.keySet();
- for(String key: keys) {
- if(resource.failsCounter.get(key) > 1) countOfThreadsNeededAtLeast2Tries++;
- }
- System.out.println("Count of threads needed at least 2 tries: " + countOfThreadsNeededAtLeast2Tries);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement