From f119a891f8b50f688257c48c4f6ef9332ab99a10 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Mon, 21 Oct 2024 12:35:46 +0200 Subject: [PATCH] [Fix] Fixed Statistics thread-safe --- .../main/java/li/strolch/agent/api/Statistics.java | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/strolch-agent/src/main/java/li/strolch/agent/api/Statistics.java b/strolch-agent/src/main/java/li/strolch/agent/api/Statistics.java index 2fd19cb59..c82159c31 100644 --- a/strolch-agent/src/main/java/li/strolch/agent/api/Statistics.java +++ b/strolch-agent/src/main/java/li/strolch/agent/api/Statistics.java @@ -1,15 +1,13 @@ package li.strolch.agent.api; import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; import java.time.Duration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; -import java.util.LinkedList; import java.util.List; import java.util.Queue; -import java.util.stream.Collectors; +import java.util.concurrent.ConcurrentLinkedQueue; import static java.time.temporal.ChronoUnit.*; @@ -18,10 +16,10 @@ public class Statistics { private final Queue events; public Statistics() { - this.events = new LinkedList<>(); + this.events = new ConcurrentLinkedQueue<>(); } - public void recordEvent(Duration duration) { + public synchronized void recordEvent(Duration duration) { LocalDateTime now = LocalDateTime.now(); this.events.add(new Statistic(now, duration)); removeOldEvents(now); @@ -53,7 +51,7 @@ public int getLastDay() { return getInTimeFrame(1, DAYS); } - private int getInTimeFrame(long amount, ChronoUnit unit) { + private synchronized int getInTimeFrame(long amount, ChronoUnit unit) { LocalDateTime now = LocalDateTime.now(); return (int) this.events .stream() @@ -61,7 +59,7 @@ private int getInTimeFrame(long amount, ChronoUnit unit) { .count(); } - public JsonObject toJson() { + public synchronized JsonObject toJson() { List durations = this.events.stream().map(e -> e.duration).toList(); long count = durations.size();