/** * Acquire the protected resource with reading privileges. Many readers can access the protected * resource at the same time, but no writer can access it while at least one reader is present. * The locking is recursive (i.e. the same thread can acquire the lock multiple times, but must * unlock it a matching number of times to actually free the protected resource). */ public synchronized void readLock() { while (currentWriter != null) { // Someone is writing the resource --> Go to sleep try { wait(); } catch (InterruptedException ie) { if (logger.isLoggable(Logger.WARNING)) logger.log(Logger.WARNING, "Unexpected interruption. " + ie.getMessage()); } } readersCnt++; }
/** * Acquire the protected resource with writing privileges. Only one writer at a time can access * the protected resource, and no readers can access it at the same time. The locking is recursive * (i.e. the same thread can acquire the lock multiple times, but must unlock it a matching number * of times to actually free the protected resource). */ public synchronized void writeLock() { Thread me = Thread.currentThread(); while ((currentWriter != null && currentWriter != me) || readersCnt > 0) { // Someone (not me) is writing the resource OR // There are one or more Threads reading the resource // --> Go to sleep try { wait(); } catch (InterruptedException ie) { if (logger.isLoggable(Logger.WARNING)) logger.log(Logger.WARNING, "Unexpected interruption. " + ie.getMessage()); } } writeLockDepth++; if (writeLockDepth == 1) { currentWriter = me; onWriteStart(); } }