package concurrency; /** * 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. */ public void read() { this.beginRead(); // read this.endRead(); } /** * Waits if a writer is writing. */ private synchronized void beginRead() { if (this.writing) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.readers++; } /** * Notifies waiting writers. */ private synchronized void endRead() { this.readers--; if (this.readers == 0) { this.notifyAll(); } } /** * Writes to this database. */ public void write() { this.beginWrite(); // write this.endWrite(); } /** * Waits if readers are reading. */ private synchronized void beginWrite() { while (this.writing || this.readers > 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.writing = true; } /** * Notifies waiting readers. */ private synchronized void endWrite() { this.writing = false; this.notifyAll(); } }