Choosing the object-to-lock in explicit locks (ReentrantLock example)

本文深入探讨了显式锁与ReentrantLock的工作原理,对比了它们与synchronized关键字的区别,通过实例展示了如何使用ReentrantLock进行线程同步,并讨论了选择锁对象的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Choosing the object-to-lock in explicit locks (ReentrantLock example)

https://coderanch.com/t/665262/java/Choosing-object-lock-explicit-locks

So, I just finished studying synchronized keyword (Blocks and methods). And here is what i basically know.

A synchronized keyword guarantees atomicity and visibility and it has to operate on two things.
1- A thread. (The calling thread)
2- An object. (The monitor object)

When using

synchronized (object) {
    //do stuff
}

The object "object" will be locked on the calling thread only. until the lock is released.

So, When i started attempting to study explicit locks, I came across this example
[Source] Java 8 Concurrency Tutorial: Synchronization and Locks - Part 2: Synchronization and Locks
https://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/

ReentrantLock

The class ReentrantLock is a mutual exclusion lock with the same basic behavior as the implicit monitors accessed via the synchronized keyword but with extended capabilities. As the name suggests this lock implements reentrant characteristics just as implicit monitors.
Let's see how the above sample looks like using ReentrantLock

ReentrantLock lock = new ReentrantLock();
int count = 0;
 
void increment() {
    lock.lock();
    try {
        count++;
    } finally {
        lock.unlock();
    }
}

Which brings me to my questions:

1- Is what's previously mentioned correct and generally accurate?
2- When using explicit locks (in the above ReentrantLock example), How do i get to choose the object that i want locked? Assuming that the calling thread is the thread that will have the lock.

You decide the policy for how and which objects to lock.

In general, you create a lock for each set of operations that should not be allowed to run concurrently.

Let's say you have an object that has two completely unrelated fields:

final class MyObject {
 
  private final Thing a = Thing.something();
  private final Thing b = Thing.something();
 
  private final Lock aLock = new ReentrantLock();
  private final Lock bLock = new ReentrantLock();
 
  int readFromA() {
    aLock.lock();
    try { return a.read(); }
    finally { aLock.unlock(); }
  }
 
  void writeToA(int val) {
    aLock.lock();
    try { a.write(val); }
    finally { aLock.unlock(); }
  }
 
  int readFromB() {
    bLock.lock();
    try { return b.read(); }
    finally { bLock.unlock(); }
  }
 
  void writeB(int val) {
    bLock.lock();
    try { b.write(val); }
    finally { bLock.unlock(); }
  }
}

Since the two fields are unrelated and the validity of the object doesn't depend on certain combinations of a and b, one thread should be allowed to interact with a while another interacts with b. To facilitate this, you need two different locks.

A big advantage of using explicit locks over implicit ones, is that a malicious class can't lock an object indefinitely while it goes off and does other things. For instance, if readFromA() used synchronized(this), any class that has access to an instance of MyObject can use a synchronized block to lock the instance, and then keep it locked forever. With explicit locks this doesn't happen, as long as you keep locks private.

Question. What "atomicity and visibility" guarantees are you referring to? Method calls? Access to instance variables?

Simply, there are no method or variable guarantees, with owning a synchronization lock on an object. The only guarantee is that only one thread can own the lock (on the object) at a time. Synchronization locks are cooperative. It is the developer's responsibility to take the "only one thread can own the lock" guarantee, and make that into visibility and atomicity guarantees.

Henry


Kotlin 开发者社区

国内第一Kotlin 开发者社区公众号,主要分享、交流 Kotlin 编程语言、Spring Boot、Android、React.js/Node.js、函数式编程、编程思想等相关主题。

1233356-bca93e5c34975635

Kotlin 开发者社区

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI天才研究院

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值