@backstreetbrogrammer
--------------------------------------------------------------------------------
Implement Read-Write Lock - FULLY REENTRANT Code Demo
--------------------------------------------------------------------------------
Suppose there is an Object obj, which is read from and written by many threads.
We need to ensure that no thread may access obj for reading or writing while another thread is writing to obj.
If no thread is writing to obj and no threads have requested write access, then multiple threads can read the obj at the same time.
Implement the synchronization mechanism which adheres to the above read-write conditions.
Re-entrance
With a reentrant lock / locking mechanism, the attempt to acquire the same lock will succeed, and will increment an internal counter belonging to the lock. The lock will only be released when the current holder of the lock has released it and counter is set to zero.
It means we can do something like this on a single thread:
1. Acquire a lock on "foo"
2. Do something
3. Acquire a lock on "foo". Note that we haven't released the lock that we previously acquired.
4. ...
5. Release lock on "foo"
6. ...
7. Release lock on "foo"
Here's an example in Java using primitive object locks / monitors which are reentrant:
final Object lock = new Object();
...
synchronized (lock) {
...
doSomething(lock, ...)
...
}
public void doSomething(Object lock, ...) {
synchronized (lock) {
...
}
}
Follow up 1 - Read re-entrance
A thread is granted read re-entrance if it can get read access (no writers or write requests), or if it already has read access (regardless of write requests).
Follow up 2 - Write re-entrance
Write re-entrance is granted only if the thread has already got write access.
Follow up 3 - Read to Write re-entrance
A thread that have read access to also obtain write access. For this to be allowed the thread must be the only reader.
Follow up 4 - Write to Read re-entrance
A thread that has got write access needs read-access too. A writer should always be granted read access if requested. If a thread has got write access, no other threads can have read nor write access.
Follow up 5 - Fully Reentrant ReadWriteLock
Combine all the above for fully re-entrant ReadWriteLock.
Github: github.com/backstreetbrogramm...
- Top Java Coding Interview Problems Playlist: • Top Java Coding Interv...
- Apache Spark for Java Developers Playlist: • Apache Spark for Java ...
- Upgrade to Java 21 Playlist: • Upgrade to Java 21
- Java Serialization Playlist: • Java Serialization
- Dynamic Programming Playlist: • Dynamic Programming
#java #javadevelopers #javaprogramming #javacodinginterview
Негізгі бет Ғылым және технология 50 - Implement Read Write Lock - FULLY REENTRANT Code Demo
Пікірлер