package lecteursRedacteurs; /** * Database.java * * This class contains the methods the readers and writers will use * to coordinate access to the database. Access is coordinated using Java synchronization. * * */ public class DataBase { public DataBase() { this.lecteurCount = 0; this.dbLectures = false; this.dbEcritures = false; this.data = new Data(12,13 ); } // readers and writers will call this to nap public static void napping() { int sleepTime = (int) (NAP_TIME * Math.random() ); try { Thread.sleep(sleepTime*1000); } catch(InterruptedException e) {} } // public String effectiveLectures() { return "["+data.getElt1()+","+data.getElt2()+"]"; } public void effectiveEcritures(int elt1, int elt2) { data.setElt1(elt1); Thread.yield(); // to force problems in case not well synchronized data.setElt2(elt2); } // reader will call this when they start reading public synchronized int startRead() { while (dbEcritures) { try { wait(); } catch(InterruptedException e) {} } ++lecteurCount; // if I am the first reader tell all others // that the database is being read if (lecteurCount == 1) dbLectures = true; return lecteurCount; } // reader will call this when they finish reading public synchronized int endRead() { --lecteurCount; // if I am the last reader tell all others // that the database is no longer being read if (lecteurCount == 0) dbLectures = false; notifyAll(); System.out.println("Lecteur Count = " + lecteurCount); return lecteurCount; } // writer will call this when they start writing public synchronized void startWrite() { while (dbLectures || dbEcritures ) { try { wait(); } catch(InterruptedException e) {} } // once there are either no readers or writers // indicate that the database is being written dbEcritures = true; } // writer will call this when they start writing public synchronized void endWrite() { dbEcritures = false; notifyAll(); } // the number of active readers private int lecteurCount; // flags to indicate whether the database is // being read or written private boolean dbLectures; private boolean dbEcritures; private Data data; private static final int NAP_TIME = 5; class Data { int elt1, elt2; Data(int pairElt1, int pairElt2){ elt1=pairElt1; elt2=pairElt2; } int getElt1() { return elt1; } int getElt2() { return elt2; } void setElt1(int elt1){ this.elt1=elt1; } void setElt2(int elt2){ this.elt2=elt2; } } }