Skip to content

Commit

Permalink
[Fix] Fixed Statistics thread-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
eitch committed Oct 21, 2024
1 parent 2b28a30 commit f119a89
Showing 1 changed file with 5 additions and 7 deletions.
12 changes: 5 additions & 7 deletions strolch-agent/src/main/java/li/strolch/agent/api/Statistics.java
Original file line number Diff line number Diff line change
@@ -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.*;

Expand All @@ -18,10 +16,10 @@ public class Statistics {
private final Queue<Statistic> 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);
Expand Down Expand Up @@ -53,15 +51,15 @@ 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()
.filter(tx -> SECONDS.between(tx.timestamp, now) < unit.getDuration().getSeconds() * amount)
.count();
}

public JsonObject toJson() {
public synchronized JsonObject toJson() {
List<Duration> durations = this.events.stream().map(e -> e.duration).toList();

long count = durations.size();
Expand Down

0 comments on commit f119a89

Please sign in to comment.