Search code examples
javasynchronizationreentrantlock

How to comparing the TPS of ReentrantLock and Synchronization


I want to measure the TPS of ReentrantLock and Synchronization.At The same Time I want draw a chart to show the change as the count of thread goes on.

But Now,I can not find a satisfied tools to complete it.The result is like this picture: The Example

Is there any tools or example that can help me achieve it?

Thank you! I have write some code,But I am not good at collecting data elegantly.

private ReentrantLock lock = new ReentrantLock();

public synchronized void testSynchronized() {
    sleepRandomTime();
}

public void testReentrantLock() {
    lock.lock();
    try {
        sleepRandomTime();
    } finally {
        lock.unlock();
    }
}

private void sleepRandomTime() {
    long sleepTime = (int) (Math.random() * 100);
    try {
        Thread.sleep(sleepTime);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
}

public class ThreadTest1 extends Thread {
    @Override
    public void run() {
        testSynchronized();
    }
}

public class ThreadTest2 extends Thread {
    @Override
    public void run() {
        testReentrantLock();
    }
}

Solution

  • For micro benchmarking I use JMH. Try it. Btw a read - write lock is orders of magnitude faster than synchronised block in cases of contention, especially if you have read operations over lapping with write operations.