The project addresses the thread synchronization problem in a library context, where readers and writers compete for synchronized access to shared resources.
The algorithm ensures that readers can read simultaneously, while writers require exclusive access to the resources.
- Readers - threads that access the library to read.
- Writers - threads that require exclusive access to the library to write.
- Library - manages access to resources, synchronizing access for both readers and writers.
To run the program, use the following command in the terminal:
java -jar .\main\target\main-1.0.jar numberOfReaders numberOfWritersIf numberOfReaders and numberOfWriters are not specified then the program asks user to enter them.
-
"Reader X wants to read"
Triggered in therequestRead(int readerId)method of theLibraryclass when a reader tries to access the library. -
"Writer X wants to write"
Triggered in therequestWrite(int writerId)method of theLibraryclass when a writer tries to access the library. -
"Reader X has entered and is reading"
Triggered in therequestRead(int readerId)method of theLibraryclass when a reader starts reading. -
"Writer X has entered and is writing"
Triggered in therequestWrite(int writerId)method of theLibraryclass when a writer starts writing. -
"Reader X has finished reading"
Triggered in thefinishRead(int readerId)method of theLibraryclass when a reader finishes reading. -
"Writer X has finished writing"
Triggered in thefinishWrite(int writerId)method of theLibraryclass when a writer finishes writing.
-
"I want to read"
Triggered in therun()method of theReaderclass when a reader tries to access the library. -
"I want to write"
Triggered in therun()method of theWriterclass when a writer tries to access the library.
- Readers can access the library's resources simultaneously.
- Writers require exclusive access to the resources.
- Synchronization relies on blocking mechanisms (
wait(),notify()) and FIFO queues.
-
wait()
Invoked by threads that must wait for certain conditions to be met:- The reader is not at the front of the queue.
- The number of readers exceeds the allowed limit (
maxReadersInside). - The writer is not at the front of the queue or other users are in the library.
-
notifyAll()
Wakes up threads waiting for library access after a reading or writing session ends.
Represents the maximum number of readers allowed in the library simultaneously.
Holds threads waiting for library access. Ensures FIFO processing.
Tracks the current number of people in the library. Uses AtomicInteger for safe operations in a multithreaded environment.
- The program supports concurrent threads for readers and writers.
- Threads perform simulated tasks such as reading and writing with random delays.
- Synchronization uses mechanisms like
synchronized,AtomicInteger, and FIFO queues.