Example usage for com.google.common.collect ConcurrentHashMultiset setCount

List of usage examples for com.google.common.collect ConcurrentHashMultiset setCount

Introduction

In this page you can find the example usage for com.google.common.collect ConcurrentHashMultiset setCount.

Prototype

@Override
public boolean setCount(E element, int expectedOldCount, int newCount) 

Source Link

Document

Sets the number of occurrences of element to newCount , but only if the count is currently expectedOldCount .

Usage

From source file:org.glyptodon.guacamole.auth.jdbc.tunnel.RestrictedGuacamoleTunnelService.java

/**
 * Attempts to add a single instance of the given value to the given
 * multiset without exceeding the specified maximum number of values. If
 * the value cannot be added without exceeding the maximum, false is
 * returned./*from   www. ja  v a2s. co m*/
 *
 * @param <T>
 *     The type of values contained within the multiset.
 *
 * @param multiset
 *     The multiset to attempt to add a value to.
 *
 * @param value
 *     The value to attempt to add.
 *
 * @param max
 *     The maximum number of each distinct value that the given multiset
 *     should hold, or zero if no limit applies.
 *
 * @return
 *     true if the value was successfully added without exceeding the
 *     specified maximum, false if the value could not be added.
 */
private <T> boolean tryAdd(ConcurrentHashMultiset<T> multiset, T value, int max) {

    // Repeatedly attempt to add a new value to the given multiset until we
    // explicitly succeed or explicitly fail
    while (true) {

        // Get current number of values
        int count = multiset.count(value);

        // Bail out if the maximum has already been reached
        if (count >= max && max != 0)
            return false;

        // Attempt to add one more value
        if (multiset.setCount(value, count, count + 1))
            return true;

        // Try again if unsuccessful

    }

}