Created
March 22, 2024 11:06
-
-
Save sidd-kulk/4ae416d96168e918ded653551a346d79 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.springbootwebcsocket.demo; | |
import java.util.concurrent.Semaphore; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import java.util.concurrent.locks.ReentrantLock; | |
//@SpringBootApplication | |
public class DemoApplication { | |
public static void main(String[] args) throws InterruptedException { | |
CounterWithLockNoRaceCondition.main(null); | |
// OptimisticLockingExample.main(null); | |
} | |
} | |
class CounterWithLockNoRaceCondition { | |
private static int counter = 0; | |
private static final Semaphore lock = new Semaphore(50); | |
public static void main(String[] args) throws InterruptedException { | |
Thread[] threads = new Thread[100000]; | |
for (int i = 0; i < 100000; i++) { | |
threads[i] = Thread.ofVirtual().start(() -> { | |
try { | |
lock.acquire(); | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
try { | |
counter++; | |
} finally { | |
lock.release(); | |
} | |
}); | |
} | |
for (Thread thread : threads) { | |
thread.join(); | |
} | |
System.out.println("Counter with lock (pessimistic locking): " + counter); | |
} | |
} | |
class OptimisticLockingExample { | |
private static AtomicInteger counter = new AtomicInteger(0); | |
public static void main(String[] args) throws InterruptedException { | |
int numThreads = 100000; | |
Thread[] threads = new Thread[numThreads]; | |
for (int i = 0; i < numThreads; i++) { | |
threads[i] = new Thread(() -> { | |
int localCounter; | |
do { | |
localCounter = counter.get(); // Get the current counter value | |
// Compare-and-swap operation | |
} while (!counter.compareAndSet(localCounter, localCounter + 1)); | |
}); | |
threads[i].start(); | |
} | |
for (Thread thread : threads) { | |
thread.join(); | |
} | |
System.out.println("Counter value after optimistic locking: " + counter); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment