Skip to content

perf: an uncontended ReentrantLock lock and unlock costs about 600 ns, 9 times a monitor #136

Done

Description

@Project516

An uncontended ReentrantLock lock and unlock costs about 550 to 600 ns on java-web, while a synchronized block costs 65 ns and a volatile read 9 to 15 ns. HotSpot on the same machine takes 22 ns for the lock and 20 ns for the monitor. Libraries that guard a getter with a ReentrantLock then pay about half a microsecond per read.

import java.util.concurrent.locks.ReentrantLock;
public class LockBench {
  static final ReentrantLock lock = new ReentrantLock();
  static final Object mon = new Object();
  static volatile long word = 3;
  static long locked() { lock.lock(); try { return word; } finally { lock.unlock(); } }
  static long synced() { synchronized (mon) { return word; } }
  public static void main(String[] a) {
    int n = 1_000_000;
    long sink = 0;
    for (int round = 0; round < 6; round++) {
      long t0 = System.nanoTime();
      for (int i = 0; i < n; i++) sink += synced();
      long t1 = System.nanoTime();
      for (int i = 0; i < n; i++) sink += locked();
      long t2 = System.nanoTime();
      System.out.printf("synchronized %.1f ns, ReentrantLock %.1f ns%n", (t1 - t0) / (double) n, (t2 - t1) / (double) n);
    }
    System.out.println(sink);
  }
}

After warm-up, on java-web 2e1388a:

Node headless Chromium HotSpot 25
volatile read 15 ns 9 ns 0.4 ns
synchronized 64 ns 68 ns 20 ns
ReentrantLock lock and unlock 600 ns 550 ns 22 ns

Expected: an uncontended ReentrantLock near the cost of a monitor, as on HotSpot. Its fast path is a compareAndSetState on an AbstractQueuedSynchronizer and a setExclusiveOwnerThread.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions