package pro.panopticon.client.responsetimelogger;

import com.amazonaws.services.cloudwatch.model.StandardUnit;
import pro.panopticon.client.awscloudwatch.CloudwatchClient;
import pro.panopticon.client.awscloudwatch.CloudwatchClient.CloudwatchStatistic;
import pro.panopticon.client.awscloudwatch.HasCloudwatchConfig;
import pro.panopticon.client.model.Measurement;
import pro.panopticon.client.sensor.Sensor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class AbstractResponseTimeLogger implements Sensor {

    private final String namespace;

    private ConcurrentMap<String, List<CloudwatchStatistic>> counts = new ConcurrentHashMap<>();

    private CloudwatchClient cloudwatchClient;

    public AbstractResponseTimeLogger(HasCloudwatchConfig hasCloudwatchConfig, CloudwatchClient cloudwatchClient) {
        this.cloudwatchClient = cloudwatchClient;
        this.namespace = String.format("responsetimes-%s-%s", hasCloudwatchConfig.getAppName(), hasCloudwatchConfig.getEnvironment());
    }

    public void addResponseTimeMeasurement(String name, long timeInMilliseconds) {
        counts.computeIfAbsent(name, n -> new ArrayList<>())
                .add(new CloudwatchStatistic(name, (double) timeInMilliseconds, StandardUnit.Milliseconds, new Date()));
    }

    @Override
    public List<Measurement> measure() {
        ConcurrentMap<String, List<CloudwatchStatistic>> toSubmit = counts;
        counts = new ConcurrentHashMap<>();
        toSubmit.forEach((key, measurements) -> cloudwatchClient.sendStatistics(namespace, measurements));

        // This sensor returns no measurements for now – it's just implemented as a sensor for similarity to the other concepts
        return Collections.emptyList();
    }

}

@@ -425,183 +425,9 @@
 til.
-ArrayList;%0Aimport java.util.Collections;%0Aimport java.util.Date;%0Aimport java.util.List;%0Aimport java.util.concurrent.ConcurrentHashMap;%0Aimport java.util.concurrent.ConcurrentMap
+*
 ;%0A%0Ap
@@ -527,46 +527,87 @@
 e;%0A%0A
+%0A
     
-private ConcurrentMap%3CString, List
+// Using Vector since it's syncronized, e.g thread safe%0A    private Vector
 %3CClo
@@ -623,17 +623,16 @@
 atistic%3E
-%3E
  counts 
@@ -637,33 +637,22 @@
 s = new 
-ConcurrentHashMap
+Vector
 %3C%3E();%0A%0A 
@@ -1107,71 +1107,8 @@
 unts
-.computeIfAbsent(name, n -%3E new ArrayList%3C%3E())%0A                
 .add
@@ -1281,30 +1281,8 @@
     
- ConcurrentMap%3CString,
  Lis
@@ -1303,17 +1303,16 @@
 atistic%3E
-%3E
  toSubmi
@@ -1315,16 +1315,21 @@
 ubmit = 
+this.
 counts;%0A
@@ -1353,78 +1353,28 @@
 new 
-ConcurrentHashMap
+Vector
 %3C%3E();%0A
+%0A
        
- toSubmit.forEach((key, measurements) -%3E
  clo
@@ -1417,21 +1417,16 @@
 ce, 
-measurements)
+toSubmit
 );%0A%0A

Make things more thread safe