开发者

When is it safe to use the readLock() method of the ReentrantReadWriteLock class?

开发者 https://www.devze.com 2023-02-17 15:04 出处:网络
It seems pretty clear that using readLock when reading from a file (for example), and using writeLock when writing to it is appropriate.However, if I have an operation where two values are being compa

It seems pretty clear that using readLock when reading from a file (for example), and using writeLock when writing to it is appropriate. However, if I have an operation where two values are being compared, such as:

if (i == j) {
    System.out.println("equal);
}

Then is it okay to use readLock() instead of writeLock to lock this code? Granted, I'm not writing anything, but I am comparing two values, which is bit different than just reading data since there is an operation involved. Keep in mind that "i" or "j" could change at any time. In theory, readLock() will only move forward if a writeLock() is not modifying the resource, but I may not fully understand all the complexities of this issue. It 开发者_开发知识库just seems like there is potential for a bit of a grey area so I thought I'd get some input.

Thanks to everyone,

Matt


Don't think about read/write locks in terms of reading and writing, think of them as exclusive/shared. A write lock is exclusive, a read lock is shared.

To answer your question, it depends.

Say you had 1 thread which was updating i, and one thread which was updating j, and another thread that was checking for equality. In that case the writing threads would acquire a shared (read) lock, since they can both operate in parallel, since each thread only updates 1 variable. The compare thread could then acquire an exclusive lock (write lock) to compare and perform an action, preventing any updates while the action was being performed.

So think in terms of exclusive/shared, and what the needs of your application are.


Though I think making i and j as volatile and synchronizing modification accesses to it should be enough.

But say that you have to use read-write locks. In that case for your above code you need to have a read-lock. The reason is your given code is a non-modification code, it doesn't modify i or j. So other methods could indeed read value of i and j parallely without any corruption. You would use write lock only in places that are modifying values of i and j.

Edit: Highlighted "synchronizing modification accesses to it" to answer the comments

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号