From dcb6ce4c51aabd73953edd33776fe8cdc3e7864f Mon Sep 17 00:00:00 2001
From: arifBurakDemiray <burakdemiray09@hotmail.com>
Date: Fri, 22 Sep 2023 16:59:18 +0300
Subject: [PATCH] refactor: to in memory cache

---
 .../sdk/java/internal/EventImplQueue.java     | 71 +++++++++----------
 .../count/sdk/java/internal/ModuleEvents.java |  9 +--
 .../sdk/java/internal/ModuleEventsTests.java  | 12 ++--
 3 files changed, 44 insertions(+), 48 deletions(-)

diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImplQueue.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImplQueue.java
index e1822d1f2..45e74aa5b 100644
--- a/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImplQueue.java
+++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/EventImplQueue.java
@@ -7,69 +7,67 @@
 public class EventImplQueue {
 
     static final String DELIMITER = ":::";
-
     private final Log L;
-
-    protected int size = 0;
     private final InternalConfig config;
+    final List<EventImpl> eventQueueMemoryCache;
 
     protected EventImplQueue(Log logger, InternalConfig config) {
         L = logger;
         this.config = config;
+        eventQueueMemoryCache = new ArrayList<>(config.getEventsBufferSize());
     }
 
-    void addEvent(final EventImpl event) {
-        L.d("[EventImplQueue] Adding event: " + event.key);
-        final List<EventImpl> events = getEventList();
-        if (events.size() < config.getEventsBufferSize()) {
-            events.add(event);
-            size = events.size();
-            setEventData(joinEvents(events));
-        }
+    /**
+     * Returns the number of events currently stored in the queue.
+     */
+    protected int eqSize() {
+        return eventQueueMemoryCache.size();
     }
 
-    String joinEvents(final Collection<EventImpl> collection) {
-        final List<String> strings = new ArrayList<>();
-        for (EventImpl e : collection) {
-            strings.add(e.toJSON(L));
+    void addEvent(final EventImpl event) {
+        L.d("[EventImplQueue] Adding event: " + event.key);
+        if (eventQueueMemoryCache.size() < config.getEventsBufferSize()) {
+            eventQueueMemoryCache.add(event);
+            writeEventQueueToStorage();
         }
-        return Utils.join(strings, EventImplQueue.DELIMITER);
     }
 
     /**
      * set the new value in event data storage
-     *
-     * @param eventData
      */
-    void setEventData(String eventData) {
-        L.d("[EventImplQueue] Setting event data: " + eventData);
-        SDKCore.instance.sdkStorage.storeEventQueue(eventData);
+    void writeEventQueueToStorage() {
+        final String eventQueue = joinEvents(eventQueueMemoryCache);
+
+        L.d("[EventImplQueue] Setting event data: " + eventQueue);
+        SDKCore.instance.sdkStorage.storeEventQueue(eventQueue);
     }
 
     /**
-     * Returns a list of the current stored events, sorted by timestamp from oldest to newest.
+     * Restores events from disk
      */
-    public synchronized List<EventImpl> getEventList() {
-        L.d("[EventImplQueue] Getting event list");
+    void restore() {
+        L.d("[EventImplQueue] Restoring events from disk");
+        eventQueueMemoryCache.clear();
+
         final String[] array = getEvents();
-        final List<EventImpl> events = new ArrayList<>(array.length);
         for (String s : array) {
 
             final EventImpl event = EventImpl.fromJSON(s, (ev) -> {
             }, L);
             if (event != null) {
-                events.add(event);
+                eventQueueMemoryCache.add(event);
             }
         }
         // order the events from least to most recent
-        events.sort((e1, e2) -> (int) (e1.timestamp - e2.timestamp));
-        size = events.size();
-        return events;
+        eventQueueMemoryCache.sort((e1, e2) -> (int) (e1.timestamp - e2.timestamp));
     }
 
-    public void clear() {
-        size = 0;
-        SDKCore.instance.sdkStorage.storeEventQueue("");
+    private String joinEvents(final Collection<EventImpl> collection) {
+        final List<String> strings = new ArrayList<>();
+        for (EventImpl e : collection) {
+            strings.add(e.toJSON(L));
+        }
+        return Utils.join(strings, EventImplQueue.DELIMITER);
     }
 
     /**
@@ -81,11 +79,8 @@ private synchronized String[] getEvents() {
         return joinedEventsStr.isEmpty() ? new String[0] : joinedEventsStr.split(DELIMITER);
     }
 
-    /**
-     * Restores events from disk
-     */
-    void restore(){
-        L.d("[EventImplQueue] Restoring events from disk");
-        getEventList();
+    public void clear() {
+        SDKCore.instance.sdkStorage.storeEventQueue("");
+        eventQueueMemoryCache.clear();
     }
 }
diff --git a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java
index 45e1ce0d0..d33d003cd 100644
--- a/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java
+++ b/sdk-java/src/main/java/ly/count/sdk/java/internal/ModuleEvents.java
@@ -7,6 +7,7 @@
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
+import javax.annotation.Nonnull;
 import ly.count.sdk.java.Countly;
 
 public class ModuleEvents extends ModuleBase {
@@ -27,9 +28,9 @@ public void init(InternalConfig config, Log logger) {
     }
 
     @Override
-    public void onContextAcquired(CtxCore ctx) {
+    public void onContextAcquired(@Nonnull CtxCore ctx) {
         this.ctx = ctx;
-        L.d("[ModuleEvents] onContextAcquired: " + ctx.toString());
+        L.d("[ModuleEvents] onContextAcquired: " + ctx);
 
         if (ctx.getConfig().getSendUpdateEachSeconds() > 0 && executor == null) {
             executor = Executors.newScheduledThreadPool(1);
@@ -52,7 +53,7 @@ private synchronized void addEventsToRequestQ() {
 
         Request request = new Request();
         request.params.add("device_id", Countly.instance().getDeviceId());
-        request.params.arr("events").put(eventQueue.getEventList()).add();
+        request.params.arr("events").put(eventQueue.eventQueueMemoryCache).add();
         request.own(ModuleEvents.class);
 
         eventQueue.clear();
@@ -95,7 +96,7 @@ protected void recordEventInternal(String key, int count, Double sum, Map<String
     private void addEventToQueue(EventImpl event) {
         L.d("[ModuleEvents] addEventToQueue");
         eventQueue.addEvent(event);
-        if (eventQueue.size >= internalConfig.getEventsBufferSize()) {
+        if (eventQueue.eqSize() >= internalConfig.getEventsBufferSize()) {
             L.d("[ModuleEvents] addEventToQueue: eventQueue.size >= internalConfig.getEventsBufferSize()");
             addEventsToRequestQ();
         }
diff --git a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleEventsTests.java b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleEventsTests.java
index 0f40e6383..72818deb3 100644
--- a/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleEventsTests.java
+++ b/sdk-java/src/test/java/ly/count/sdk/java/internal/ModuleEventsTests.java
@@ -52,7 +52,7 @@ public void start() {
     @Test
     public void recordEvent() {
         moduleEvents.eventQueue.clear();
-        Assert.assertEquals(0, moduleEvents.eventQueue.size);
+        Assert.assertEquals(0, moduleEvents.eventQueue.eqSize());
 
         //create segmentation
         Map<String, Object> segmentation = new HashMap<>();
@@ -65,7 +65,7 @@ public void recordEvent() {
 
         //check if event was recorded correctly and size of event queue is equal to size of events in queue
         List<EventImpl> events = TestUtils.getCurrentEventQueue(moduleEvents.ctx.getContext(), moduleEvents.L);
-        Assert.assertEquals(1, moduleEvents.eventQueue.size);
+        Assert.assertEquals(1, moduleEvents.eventQueue.eqSize());
         Assert.assertEquals(1, events.size());
 
         //check if event was recorded correctly
@@ -85,7 +85,7 @@ public void recordEvent() {
     public void recordEvent_fillEventQueue() {
         recordEvent(); // fill the queue
         try {
-            Assert.assertEquals(1, moduleEvents.eventQueue.size);
+            Assert.assertEquals(1, moduleEvents.eventQueue.eqSize());
 
             //create segmentation
             Map<String, Object> segmentation = new HashMap<>();
@@ -100,7 +100,7 @@ public void recordEvent_fillEventQueue() {
             List<EventImpl> events = TestUtils.getCurrentEventQueue(moduleEvents.ctx.getContext(), moduleEvents.L);
             EventImpl q1 = events.get(0);
             EventImpl q2 = events.get(1);
-            Assert.assertEquals(2, moduleEvents.eventQueue.size);
+            Assert.assertEquals(2, moduleEvents.eventQueue.eqSize());
             Assert.assertEquals(2, events.size());
             Assert.assertEquals("test-recordEvent", q1.key);
             Assert.assertEquals(67, q1.segmentation.get("weight"));
@@ -119,7 +119,7 @@ public void recordEvent_fillEventQueue() {
     @Test
     public void recordEvent_reInitCountly() {
         moduleEvents.eventQueue.clear();
-        Assert.assertEquals(0, moduleEvents.eventQueue.size);
+        Assert.assertEquals(0, moduleEvents.eventQueue.eqSize());
 
         //create segmentation
         Map<String, Object> segmentation = new HashMap<>();
@@ -137,7 +137,7 @@ public void recordEvent_reInitCountly() {
 
         //check if event was recorded correctly and size of event queue is equal to size of events in queue
         List<EventImpl> events = TestUtils.getCurrentEventQueue(moduleEvents.ctx.getContext(), moduleEvents.L);
-        Assert.assertEquals(1, moduleEvents.eventQueue.size);
+        Assert.assertEquals(1, moduleEvents.eventQueue.eqSize());
         Assert.assertEquals(1, events.size());
 
         //check if event was recorded correctly