Search code examples
javamultithreadingreentrantreadwritelock

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


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


Solution

  • 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.