From e9a8ff0a259453eac93e24e87ebcc9142702c71c Mon Sep 17 00:00:00 2001 From: Sriram Rangarajan Date: Wed, 14 Dec 2022 11:58:19 -0800 Subject: [PATCH] Sort Clients for add --- .../java/com/netflix/evcache/EVCacheImpl.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/evcache-core/src/main/java/com/netflix/evcache/EVCacheImpl.java b/evcache-core/src/main/java/com/netflix/evcache/EVCacheImpl.java index 6651f142..b17450b3 100644 --- a/evcache-core/src/main/java/com/netflix/evcache/EVCacheImpl.java +++ b/evcache-core/src/main/java/com/netflix/evcache/EVCacheImpl.java @@ -20,6 +20,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Function; +import java.util.stream.Collectors; import javax.management.MBeanServer; import javax.management.ObjectName; @@ -3259,7 +3260,21 @@ public boolean add(String key, T value, Transcoder tc, int timeToLive) th @Override public EVCacheLatch add(String key, T value, Transcoder tc, int timeToLive, Policy policy) throws EVCacheException { EVCacheClient[] clients = _pool.getEVCacheClientForWrite(); - return this.add(key, value, tc, timeToLive, policy, clients, clients.length - _pool.getWriteOnlyEVCacheClients().length); + EVCacheClient[] writeOnlyClients = _pool.getWriteOnlyEVCacheClients(); + // In case of adds , we skip adds to the pool if value is already present in the 1st client + // Sorting to make sure the 1st element of the list is a read/write client and not just write-only client + EVCacheClient[] sortedClients = sortClients(clients, writeOnlyClients); + return this.add(key, value, tc, timeToLive, policy, sortedClients, clients.length - _pool.getWriteOnlyEVCacheClients().length); + } + + public EVCacheClient[] sortClients(EVCacheClient[] clients, EVCacheClient[] writeOnlyClients) { + List writeOnlyClientsList = Arrays.asList(writeOnlyClients); + List clientList = Arrays.stream(clients).sorted((s1, s2) -> { + if (writeOnlyClientsList.contains(s1)) + return 1; + return -1; + }).collect(Collectors.toList()); + return clientList.stream().toArray(EVCacheClient[]::new); } protected EVCacheLatch add(String key, T value, Transcoder tc, int timeToLive, Policy policy, EVCacheClient[] clients, int latchCount) throws EVCacheException {