Search in sources :

Example 1 with JDAImpl

use of net.dv8tion.jda.core.entities.impl.JDAImpl in project FredBoat by Frederikam.

the class JDAUtil method countUniqueUsers.

/**
 * A count of unique users over the provided shards. This is an expensive operation given FredBoats scale.
 * <p>
 * Optionally pass in a value of value of previous counts / expected size to that we can initialize the set used
 * to count the unique values with an approriate size reducing expensive resizing operations.
 */
@CheckReturnValue
public static int countUniqueUsers(@Nonnull Collection<JDA> shards, @Nullable AtomicInteger expectedUserCount) {
    if (shards.size() == 1) {
        // a single shard provides a cheap call for getting user cardinality
        return Math.toIntExact(shards.iterator().next().getUserCache().size());
    }
    int expected = expectedUserCount != null && expectedUserCount.get() > 0 ? expectedUserCount.get() : LongOpenHashSet.DEFAULT_INITIAL_SIZE;
    // add 10k for good measure
    LongOpenHashSet uniqueUsers = new LongOpenHashSet(expected + 10000);
    TObjectProcedure<User> adder = user -> {
        uniqueUsers.add(user.getIdLong());
        return true;
    };
    Collections.unmodifiableCollection(shards).forEach(// this means however, that for the (small) duration, the map cannot be used by other threads (if there are any)
    shard -> ((JDAImpl) shard).getUserMap().forEachValue(adder));
    return uniqueUsers.size();
}
Also used : CheckReturnValue(javax.annotation.CheckReturnValue) LongOpenHashSet(it.unimi.dsi.fastutil.longs.LongOpenHashSet) JDAImpl(net.dv8tion.jda.core.entities.impl.JDAImpl) User(net.dv8tion.jda.core.entities.User) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TObjectProcedure(gnu.trove.procedure.TObjectProcedure) Collection(java.util.Collection) JDA(net.dv8tion.jda.core.JDA) Nonnull(javax.annotation.Nonnull) Collections(java.util.Collections) Nullable(javax.annotation.Nullable) User(net.dv8tion.jda.core.entities.User) JDAImpl(net.dv8tion.jda.core.entities.impl.JDAImpl) LongOpenHashSet(it.unimi.dsi.fastutil.longs.LongOpenHashSet) CheckReturnValue(javax.annotation.CheckReturnValue)

Aggregations

TObjectProcedure (gnu.trove.procedure.TObjectProcedure)1 LongOpenHashSet (it.unimi.dsi.fastutil.longs.LongOpenHashSet)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 CheckReturnValue (javax.annotation.CheckReturnValue)1 Nonnull (javax.annotation.Nonnull)1 Nullable (javax.annotation.Nullable)1 JDA (net.dv8tion.jda.core.JDA)1 User (net.dv8tion.jda.core.entities.User)1 JDAImpl (net.dv8tion.jda.core.entities.impl.JDAImpl)1