import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class LockPerformanceTest {
private static final int THREAD_COUNT = 100;
private static final int ITERATIONS = 1000000;
private static int counter = 0;
private static Lock lock = new ReentrantLock();
private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private static Lock readLock = readWriteLock.readLock();
private static Lock writeLock = readWriteLock.writeLock();
public static void main(String[] args) throws InterruptedException {
runSynchronizedTest();
runReentrantLockTest();
runReadWriteLockTest();
}
private static void runSynchronizedTest() throws InterruptedException {
long startTime = System.currentTimeMillis();
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < ITERATIONS; j++) {
synchronized (LockPerformanceTest.class) {
counter++;
}
}
});
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
long endTime = System.currentTimeMillis();
System.out.println("synchronized performance: " + (endTime - startTime) + " ms");
}
private static void runReentrantLockTest() throws InterruptedException {
long startTime = System.currentTimeMillis();
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < ITERATIONS; j++) {
lock.lock();
try {
counter++;
} finally {
lock.unlock();
}
}
});
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
long endTime = System.currentTimeMillis();
System.out.println("ReentrantLock performance: " + (endTime - startTime) + " ms");
}
private static void runReadWriteLockTest() throws InterruptedException {
long startTime = System.currentTimeMillis();
Thread[] threads = new Thread[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < ITERATIONS; j++) {
readLock.lock();
try {
counter++;
} finally {
readLock.unlock();
}
}
});
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
long endTime = System.currentTimeMillis();
System.out.println("ReadWriteLock performance: " + (endTime - startTime) + " ms");
}
}