Thursday, April 17, 2014

Refined Readers Writers solution

Here's an improved version of Readers writers where i have used Semaphore class provide in java.util.concurrent package . . . Tell me if any changes required

ReadersWriters.java

import java.util.Scanner;
import java.util.concurrent.Semaphore;
public class ReadersWriters
{
public static void main(String[] args)
{
System.out.println("Enter the number of Readers : ");
Scanner sc = new Scanner(System.in);
int totalReaders = sc.nextInt();
Reader reader[] = new Reader[totalReaders];
System.out.println("Enter the number of Writers : ");
int totalWriters = sc.nextInt();
Writer writer[] = new Writer[totalWriters];
Database db = new Database(0);
Semaphore semDB = new Semaphore(1);
Semaphore semRC = new Semaphore(1);
for(int i=0;i<totalReaders;i++)
{
reader[i] = new Reader(i,db,semRC,semDB);
new Thread(reader[i]).start();
}
for(int i=0;i<totalWriters;i++)
{
writer[i] = new Writer(i,db,semDB);
new Thread(writer[i]).start();
}
}
}
class Reader implements Runnable
{
int rno;
Database db;
Semaphore semDB;
Semaphore semRC;
Reader(int rno, Database db, Semaphore semDB, Semaphore semRC)
{
this.rno = rno;
this.db = db;
this.semDB = semDB;
this.semRC = semRC;
}
public void run()
{
try{
semRC.acquire(); //acquire lock on reader Count
db.rc++; //Increment Reader Count
semRC.release(); // release the lock on reader count
if(db.rc == 1) // Check if only one reader
{
db.rc--;
semDB.acquire(); // Acquire lock on value of database or Enter the Critical section
System.out.println("Value read by the reader "+this.rno+" is :"+db.read());
Thread.sleep(2000);
semDB.release(); // Exit from the critical section
}
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
}
class Writer implements Runnable
{
int wno;
Database db;
Semaphore semDB;
Writer(int wno, Database db,Semaphore semDB)
{
this.wno = wno;
this.db = db;
this.semDB = semDB;
}
public void run()
{
try{
semDB.acquire(); // Entering the Critical Section
System.out.println("Writer "+this.wno+" is writing value "+(this.wno+10)+" to the Database...");
db.write(this.wno+10); // Writing the value to the Database
Thread.sleep(2000);
semDB.release(); // leaving the Critical Section
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
}
class Database
{
int value;
int rc;
Database(int value)
{
this.value = value;
this.rc = 0;
}
int read()
{
return this.value;
}
void write(int value)
{
this.value = value;
}

}

No comments:

Post a Comment