/** * A database that can be read by multiple readers * at the same time, but can only be written by a * single writer. * * @author Franck van Breugel */ public class Database { private boolean writing; private int readers; /** * Initializes this database. */ public Database() { this.writing = false; this.readers = 0; } /** * Reads this database. * * @throws InterruptedException if thread is interrupted while * waiting to read. */ public void read() throws InterruptedException { synchronized (this) { while (this.writing) { this.wait(); } this.readers++; } // read synchronized (this) { this.readers--; if (this.readers == 0) { this.notify(); } } } /** * Writes to this database. * * @throws InterruptedException if thread is interrupted while * waiting to write. */ public void write() throws InterruptedException { synchronized (this) { while (this.writing || this.readers > 0) { this.wait(); } this.writing = true; } // write synchronized (this) { this.writing = false; this.notifyAll(); } } }