Question: Q:give me output for this code and call the class main package shreddatabase; import java.util.concurrent.Semaphore; public class SharedDatabase { // Semaphore to control access to
Q:give me output for this code and call the class main
package shreddatabase;
import java.util.concurrent.Semaphore;
public class SharedDatabase { // Semaphore to control access to the database private Semaphore semaphore; // Count of the number of readers currently accessing the database private int readerCount; // The shared data in the database private int data;
public SharedDatabase() { this.semaphore = new Semaphore(1); this.readerCount = 0; } public int readData() throws InterruptedException { // Acquire the semaphore semaphore.acquire(); // Increment the number of readers readerCount++; // If this is the first reader, acquire the semaphore again to prevent writers from accessing if (readerCount == 1) { semaphore.acquire(); } // Release the semaphore semaphore.release(); // Read the data int readData = data; // Acquire the semaphore semaphore.acquire(); // Decrement the number of readers readerCount--; // If this is the last reader, release the semaphore to allow writers to access if (readerCount == 0) { semaphore.release(); } // Release the semaphore semaphore.release(); // Return the read data return readData; }
public void writeData(int data) throws InterruptedException { // Acquire the semaphore to prevent readers and other writers from accessing semaphore.acquire(); // Write the data this.data = data; // Release the semaphore to allow readers and other writers to access semaphore.release(); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
