/** * Attempts to acquire in exclusive mode. This method should query if the * state of the object permits it to be acquired in the exclusive mode, and if * so to acquire it. * * <p> * This method is always invoked by the thread performing acquire. If this * method reports failure, the acquire method may queue the thread, if it is * not already queued, until it is signalled by a release from some other * thread. * * @return true if the acquire succeeded and false otherwise */ private final boolean tryAcquire() { if (compareAndSet(0, WRITE_MASK)) { this.sync.setOwnerThread(); return true; } else { return false; } }
+ currentState); if (compareAndSet(currentState, currentState + 1)) { return true;
/** * Attempts to set the state to reflect a release in exclusive mode. * * <p> * This method is always invoked by the thread performing release. * * @throws IllegalMonitorStateException * if releasing would place this synchronizer in an illegal state. * This exception must be thrown in a consistent fashion for * synchronization to work correctly. */ private final void tryRelease() { if (compareAndSet(WRITE_MASK, 0)) { this.sync.clearOwnerThread(); } else { // if system is going down then this can happen in some rare cases getCancelCriterion().checkCancelInProgress(null); throw new IllegalMonitorStateException("write lock not held in release"); } }
/** * Attempts to set the state to reflect a release in shared mode. * * <p> * This method is always invoked by the thread performing release. * * @throws IllegalMonitorStateException * if releasing would place this synchronizer in an illegal state. * This exception must be thrown in a consistent fashion for * synchronization to work correctly. */ private final void tryReleaseShared() { for (;;) { final int currentState = getState(); if (currentState <= 0) { // if system is going down then this can happen in some rare cases getCancelCriterion().checkCancelInProgress(null); throw new IllegalMonitorStateException( "read lock count is <= zero in release = " + currentState); } if (compareAndSet(currentState, currentState - 1)) { return; } } } }