tryConsume

fun tryConsume(tokensToConsume: Long): Boolean(source)

Tries to consume the specified number of tokensToConsume. Delegates directly to the underlying LockFreeBucket's tryConsume implementation.

Return

true if the tokens were consumed, false otherwise.

Parameters

tokensToConsume

The number of tokens to try and consume from the bucket. Must be a positive value.


suspend fun tryConsume(tokensToConsume: Long, maxWaitTime: Duration): Boolean(source)

Tries to consume the specified number of tokensToConsume, suspending up to maxWaitTime if necessary in order to accumulate enough tokens to consume the specified amount.

The (slightly simplified) logic is as follows:

  • if tokensToConsume tokens are available, consume them and return true immediately

  • else if enough tokens will be made available to satisfy tokensToConsume within maxWaitTime, the function will delay until the requisite number of tokens are available, consume them, and return true.

  • else, will immediately return false.

It should also be noted that this function is fair: If invoked twice without enough tokens for the first request to succeed, the first request will be serviced before subsequent requests.

This algorithm is a direct copy of Bucket4j BlockingBucket's tryConsume, except it suspends the calling coroutine's execution while waiting for available tokens, rather than blocking the thread. See the Bucket4j tryConsume documentation for more details.

Return

true if the tokens were consumed, false otherwise.

Parameters

tokensToConsume

The number of tokens to try and consume from the bucket. Must be a positive value.

maxWaitTime

The maximum amount of time to wait for the bucket to refill enough tokens such that the requested tokensToConsume can be consumed.