Wk5L1 - Locks Flashcards
What is a ReentrantLock?
A ReentrantLock allows the same thread to acquire the lock multiple times. It maintains a count of how many times it has been locked. All locks must be released before another thread can execute.
When is a Reader-Writer Lock useful?
A Reader-Writer Lock is useful when multiple threads frequently read shared data, but only occasionally write to it. It allows multiple threads to read simultaneously but only one thread to write.
What are the two types of locks in a Reader-Writer Lock?
Shared Read Lock: Allows multiple threads to read the variable simultaneously (ReentrantReadWriteLock.ReadLock).
Exclusive Write Lock: Allows only one thread to modify the variable at a time (ReentrantReadWriteLock.WriteLock).
What is the Fairness Policy in ReentrantLocks?
The fairness policy ensures that the thread waiting the longest gets access to the lock. You can enable this by passing true to the lock’s constructor.
What are the downsides of using the Fairness Policy?
While the fairness policy ensures the longest waiting thread gets the lock, it can result in slower overall execution time, as thread scheduling is controlled by the operating system.
How does a ReentrantReadWriteLock improve performance for read-heavy applications?
By allowing multiple threads to read simultaneously without blocking, a ReentrantReadWriteLock reduces waiting time for threads that only need to read data, improving overall throughput.