Monday, January 24, 2022

Locking : Best Practices

 


Read Lock:

Read lock allows multiple thread to acquire lock in read method when all the synchronizing threads are using only the read lock of the Reentrant Read Write Lock pair.

If any thread is using the write lock of Reentrant Read Write Lock pair, read lock on resource is not allowed

Write Lock : Write lock allows only one thread to acquire lock in write method.All the other synchronizing threads will have to wait for the lock to be released before they can acquire read or write lock on resource

ReadWriteLock rwLock = new ReentrantReadWriteLock();

Lock readLock = rwLock.readLock();

Lock writeLock = rwLock.writeLock();

readLock.lock();

try {

    // reading data

} finally {

    readLock.unlock();

}

writeLock.lock();

try {

    // update data

} finally {

    writeLock.unlock();

}

No comments:

Post a Comment