HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Reader-writers problem using semaphores in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
problemwritersjavausingsemaphoresreader

Problem

I have written my own solution to the Reader-Writers problems using semaphores based on the psuedocode from Wikipedia. I would like to gauge the correctness and quality of the code.

```
import java.util.concurrent.Semaphore;

class ReaderWritersProblem {

static Semaphore readLock = new Semaphore(1);
static Semaphore writeLock = new Semaphore(1);
static int readCount = 0;

static class Read implements Runnable {
@Override
public void run() {
try {
//Acquire Section
readLock.acquire();
readCount++;
if (readCount == 1) {
writeLock.acquire();
}
readLock.release();

//Reading section
System.out.println("Thread "+Thread.currentThread().getName() + " is READING");
Thread.sleep(1500);
System.out.println("Thread "+Thread.currentThread().getName() + " has FINISHED READING");

//Releasing section
readLock.acquire();
readCount--;
if(readCount == 0) {
writeLock.release();
}
readLock.release();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}

static class Write implements Runnable {
@Override
public void run() {
try {
writeLock.acquire();
System.out.println("Thread "+Thread.currentThread().getName() + " is WRITING");
Thread.sleep(2500);
System.out.println("Thread "+Thread.currentThread().getName() + " has finished WRITING");
writeLock.release();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}

public static void main(String[] args) throws Exception {
Read read =

Solution

There's no need to use synchronize for readers, as you are acquiring the lock for readCount++ and readCount--.

One drawback in your code is the starvation for writers. The first reader has acquired writeLock, and so subsequent readers will keep on coming and will not let readCount become 0. So any waiting writers will always wait for writeLock to be released and will eventually starve.

Context

StackExchange Code Review Q#127234, answer score: 3

Revisions (0)

No revisions yet.