public class Database { private int activeReaders; private boolean writing; public Database() { this.activeReaders = 0; this.writing = false; } public void read() { synchronized (this) { while (this.writing) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.activeReaders++; } // read synchronized (this) { this.activeReaders--; if (this.activeReaders == 0) { this.notify(); } } } public void write() { synchronized (this) { while (this.activeReaders != 0 || this.writing) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.writing = true; } // write synchronized (this) { this.writing = false; this.notifyAll(); } } }