@ SuppressWarnings ( "GoodTime" ) // should accept a java.time.Duration public boolean enterWhen ( Guard guard , long time , TimeUnit unit ) throws InterruptedException { final long timeoutNanos = toSafeNanos ( time , unit ) ; if ( guard . monitor != this ) { throw new IllegalMonitorStateException ( ) ; } final ReentrantLock lock = this . lock ; boolean reentrant = lock . isHeldByCurrentThread ( ) ; long startTime = 0L ; locked : { if ( ! fair ) { // Check interrupt status to get behavior consistent with fair case. if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } if ( lock . tryLock ( ) ) { break locked ; } } startTime = initNanoTime ( timeoutNanos ) ; if ( ! lock . tryLock ( time , unit ) ) { return false ; } } boolean satisfied = false ; boolean threw = true ; try { satisfied = guard . isSatisfied ( ) || awaitNanos ( guard , ( startTime == 0L ) ? timeoutNanos : remainingNanos ( startTime , timeoutNanos ) , reentrant ) ; threw = false ; return satisfied ; } finally { if ( ! satisfied ) { try { // Don't need to signal if timed out, but do if interrupted if ( threw && ! reentrant ) { signalNextWaiter ( ) ; } } finally { lock . unlock ( ) ; } } } }
Enters this monitor when the guard is satisfied . Blocks at most the given time including both the time to acquire the lock and the time to wait for the guard to be satisfied and may be interrupted .