I am trying to understand the workings of reader writer locks. For the sake of learning, I implemented reader writer synchronization by my own. I implemented SynchronizedArrayList
with reader writer synchronization.
I set out with following objective:
- There can be many readers.
- There can only be just one writer.
- Fairness among writers. In other words, writers should be served in FIFO manner.
I request reviewers to provide feedback on following:
- Correctness of code by considering the above set objectives.
- Efficiency of code.
- Any other improvements.
import java.util.ArrayList;
public class SynchronizedArrayList {
private ArrayList<Object> list = new ArrayList<Object>();
private int readerCount = 0;
public void add(int index, Object obj)
{
synchronized(this) {
while (readerCount != 0)
waitForSignal();
addInternal(index, obj);
}
}
public Object get(int index) {
synchronized(this) {
readerCount++;
}
Object toReturn = getInternal(index);
synchronized(this) {
readerCount--;
if (readerCount == 0) {
this.notify();
}
}
return toReturn;
}
private Object getInternal(int index) {
return list.get(index);
}
private void addInternal(int index, Object obj) {
list.add(index, obj);
}
private void waitForSignal() {
//not yet implemented
}
}