public long tryConsume(){
  do {
    final long now=ticker.read();
    final State currentState=state.get();
    final State newState;
    if (currentState == null || isExpired(now)) {
      newState=new State(capacity - 1,now);
    }
 else {
      long timestampLastRefill=currentState.timestampLastRefill;
      long counter=currentState.counter;
      long newTokens=tokensThatCanBeAdded(now,currentState);
      if (newTokens > 0) {
        newTokens=Math.min(newTokens,capacity - currentState.counter);
        counter+=newTokens;
        timestampLastRefill=currentState.timestampLastRefill + newTokens * nanosToWaitForNextToken;
      }
      if (counter <= 0) {
        long delayForNextRetry=(currentState.timestampLastRefill + this.nanosToWaitForNextToken) - now;
        return Math.max(1,delayForNextRetry);
      }
      counter--;
      newState=new State(counter,timestampLastRefill);
    }
    if (state.compareAndSet(currentState,newState)) {
      return 0;
    }
  }
 while (true);
}

public long tryConsume ( ) { do { final long now = ticker . read ( ) ; final State currentState = state . get ( ) ; final State newState ; if ( currentState == null || isExpired ( now ) ) { newState = new State ( capacity - 1 , now ) ; } else { long timestampLastRefill = currentState . timestampLastRefill ; long counter = currentState . counter ; long newTokens = tokensThatCanBeAdded ( now , currentState ) ; if ( newTokens > 0 ) { newTokens = Math . min ( newTokens , capacity - currentState . counter ) ; counter += newTokens ; timestampLastRefill = currentState . timestampLastRefill + newTokens * nanosToWaitForNextToken ; } if ( counter <= 0 ) { long delayForNextRetry = ( currentState . timestampLastRefill + this . nanosToWaitForNextToken ) - now ; return Math . max ( 1 , delayForNextRetry ) ; } counter -- ; newState = new State ( counter , timestampLastRefill ) ; } if ( state . compareAndSet ( currentState , newState ) ) { return 0 ; } } while ( true ) ; }
consume a token from the bucket . the returned delay is just an indication , and event if wait for that delay , there is no guarantee that this next call will succeed .
