![]() initialElements) As you can see, this program creates and runs 10 reader threads and 2 writer threads that work on a shared ReadWriteList data structure. Private ReadWriteLock rwLock = new ReentrantReadWriteLock() * features to a non-threadsafe collection * This class demonstrates how to use ReadWriteLock to add concurrency Consider the following data structure: import java.util.* Let’s see an example that adds concurrency features to an ArrayList using ReentrantReadWriteLock. So ReadWriteLock can be used to add concurrency features to a data structure, but it doesn’t guarantee the performance because it depends on various factors: how the data structure is designed, the contention of reader and writer threads at real time, CPU architecture (single core or multicores), etc.Similar to ReentrantLock, the ReentrantReadWriteLock allows a thread to acquire the read lock or write lock multiple times recursively, thus the word “Reentrant”. ![]() If a thread attempts to update the data while other threads are reading, the write thread also blocks until the read lock is released. ![]() Only one thread can update the data at a time, causing other threads (both readers and writers) block until the write lock is released.Multiple threads can read the data at the same time, as long as there’s no thread is updating the data.}A ReadWriteLock implementation guarantees the following behaviors: }And use the write lock to safeguard a code block that performs update operation like this: writeLock.lock() Lock writeLock = rwLock.writeLock() Then you can use the read lock to safeguard a code block that performs read operation like this: readLock.lock() So you can create a ReadWriteLock like this: ReadWriteLock rwLock = new ReentrantReadWriteLock() The ReentrantReadWriteLock maintains two separate locks, one for reading and one for writing: Lock readLock = rwLock.readLock() ReadWriteLock is an interface defined in the package, with ReentrantReadWriteLock is an implementation class. In this Java concurrency tutorial, you will understand how ReadWriteLock works and use it for simple cases with ReentrantReadWriteLock implementation.Basically, a ReadWriteLock is designed as a high-level locking mechanism that allows you to add thread-safety feature to a data structure while increasing throughput by allowing multiple threads to read the data concurrently and one thread to update the data exclusively.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |