ReadWriteLock in Java

ReadWriteLock is an interface that extends the base Lock interface. It is used to improve performance in a multithreaded process and operates on a couple of related locks (one for read operations, the other for writes). A read lock can be held simultaneously by multiple reading threads until a writer appears. The write lock is exclusive.

There is a class ReentrantReadWriteLock that implements the ReadWriteLock interface, which supports up to 65535 write locks and up to the same number of read locks.

ReadWriteLock rwLock = new ReentrantReadWriteLock();
Lock rLock = rwLock.readLock();
Lock wLock = rwLock.writeLock();

wLock.lock();
try {
    // exclusive write
} finally {
    wLock.unlock();
}
        
rLock.lock();
try {
    // shared reading
} finally {
    rLock.unlock();
}

What is a "blocking method"?

Blocking method - a method that blocks until the task is completed, for example, the accept() method of the ServerSocket is blocked while waiting for a client connection. Here, blocking means that control will not return to the calling method until the job is done. There are also asynchronous or non-blocking methods that can complete before the task is completed.


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed