Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Q: run this code in NetBeans and give me the modification and output package sdh; import java.util.concurrent.Semaphore; public class Sdh { private Semaphore s; //

Q: run this code in NetBeans and give me the modification and output

package sdh; import java.util.concurrent.Semaphore; public class Sdh { private Semaphore s; // Semaphore to control access to the database private int r; // Count of the number of readers currently accessing the database private int data; // The shared data in the database public Sdh() { this.s = new Semaphore(1); this.r = 0; } public int readData() throws InterruptedException { s.acquire(); // Acquire the semaphore r++; // Increment the number of readers if (r == 1) { // If this is the first reader, acquire the semaphore again to prevent writers from accessing s.acquire(); } s.release(); // Release the semaphore int readData = data; // Read the data s.acquire(); // Acquire the semaphore r--; // Decrement the number of readers if (r == 0) { // If this is the last reader, release the semaphore to allow writers to access s.release(); } s.release(); // Release the semaphore return readData; // Return the read data } public void writeData(int data) throws InterruptedException { // Acquire the semaphore to prevent readers and other writers from accessing s.acquire(); // Write the data this.data = data; // Release the semaphore to allow readers and other writers to access s.release(); } public static void main(String[] args) { Sdh sharedDatabase = new Sdh(); try { sharedDatabase.writeData(5); int readData = sharedDatabase.readData(); System.out.println("Read data: " + readData); } catch (InterruptedException e) { e.printStackTrace(); } } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Essential SQLAlchemy Mapping Python To Databases

Authors: Myers, Jason Myers

2nd Edition

1491916567, 9781491916568

More Books

Students also viewed these Databases questions

Question

Understand why empowerment is so important in many frontline jobs.

Answered: 1 week ago