Skip to content

Commit

Permalink
add filter to UpdateAgent
Browse files Browse the repository at this point in the history
  • Loading branch information
HSGamer committed Jan 28, 2025
1 parent 85111aa commit 547135c
Showing 1 changed file with 16 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@
import me.hsgamer.topper.core.DataEntry;
import me.hsgamer.topper.core.DataHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand All @@ -17,6 +20,7 @@ public class UpdateAgent<K, V> implements DataEntryAgent<K, V>, Runnable {
private final Queue<K> updateQueue = new ConcurrentLinkedQueue<>();
private final DataHolder<K, V> holder;
private final Function<K, CompletableFuture<Optional<V>>> updateFunction;
private final List<Predicate<K>> filters = new ArrayList<>();
private int maxEntryPerCall = 10;

public UpdateAgent(Logger logger, DataHolder<K, V> holder, Function<K, CompletableFuture<Optional<V>>> updateFunction) {
Expand All @@ -29,6 +33,14 @@ public void setMaxEntryPerCall(int maxEntryPerCall) {
this.maxEntryPerCall = maxEntryPerCall;
}

public void addFilter(Predicate<K> filter) {
filters.add(filter);
}

private boolean canUpdate(K key) {
return filters.stream().allMatch(predicate -> predicate.test(key));
}

@Override
public void run() {
for (int i = 0; i < maxEntryPerCall; i++) {
Expand All @@ -37,8 +49,10 @@ public void run() {
break;
}
DataEntry<K, V> entry = holder.getOrCreateEntry(k);
updateFunction.apply(k)
.thenAcceptAsync(optional -> optional.ifPresent(entry::setValue))
(canUpdate(k)
? updateFunction.apply(k).thenAcceptAsync(optional -> optional.ifPresent(entry::setValue))
: CompletableFuture.completedFuture(null)
)
.whenComplete((v, throwable) -> {
if (throwable != null) {
logger.log(Level.WARNING, "An error occurred while updating the entry: " + k, throwable);
Expand Down

0 comments on commit 547135c

Please sign in to comment.