← 中文资源

简体中文版本

实例锁与类锁互不排斥

实例监视器和 Class 对象上的监视器是两把不同的锁:一个线程持有实例锁时,类锁与另一个实例的锁照样能进入,各保护各的状态。示例里 holder 进入 a 的 instanceLock 后,主线程仍能拿 b 的实例锁与类锁,共享的 sharedTotal 被两种锁交错自增,正是混用锁的风险。

阅读英文原文

实现说明

真正干活的是类 LockScopeMismatch、monitor、lock和函数 bumpWithClassLock、sleepQuietly,其余都是接线。

使用要点

  • 每一步打印都带着自己的标签:holder entered a's instance lock、holder still inside the critical section、b's instance lock taken while a's is held。
  • main 按顺序串起 bumpWithClassLock、sleepQuietly;运行文件就会把这个流程跑一遍。

常见问题

运行「实例锁与类锁互不排斥」会打印什么?

运行文件本身,holder entered a's instance lock、holder still inside the critical section、b's instance lock taken while a's is held 这些前缀各对应一段演示逻辑。

主要签名是 static void bumpWithClassLock()

核心语句

synchronized (LockScopeMismatch.class) { // the class monitor is a different lock
    sharedTotal++;
}
synchronized (instanceLock) {            // one monitor per object instance
    sharedTotal++;
}
Thread.sleep(100); // let the holder enter first
synchronized (b.instanceLock) {
    System.out.println("b's instance lock taken while a's is held");
}

代码示例

public class LockScopeMismatch {

    private static int sharedTotal = 0;
    private final Object instanceLock = new Object();

    void bumpWithInstanceLock() {
        synchronized (instanceLock) {            // one monitor per object instance
            sharedTotal++;
        }
    }

    static void bumpWithClassLock() {
        synchronized (LockScopeMismatch.class) { // the class monitor is a different lock
            sharedTotal++;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        LockScopeMismatch a = new LockScopeMismatch();
        LockScopeMismatch b = new LockScopeMismatch();
        a.bumpWithInstanceLock();
        b.bumpWithInstanceLock();
        bumpWithClassLock();

        Thread holder = new Thread(() -> {
            synchronized (a.instanceLock) {
                System.out.println("holder entered a's instance lock");
                sleepQuietly(300);
                System.out.println("holder still inside the critical section");
            }
        });
        holder.start();
        Thread.sleep(100); // let the holder enter first

        synchronized (b.instanceLock) {
            System.out.println("b's instance lock taken while a's is held");
        }
        synchronized (LockScopeMismatch.class) {
            System.out.println("class lock taken while a's instance lock is held");
        }
        holder.join();
        System.out.println("sharedTotal = " + sharedTotal);
    }

    private static void sleepQuietly(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}