From fb1c1f3f02cca6fcbec27abea8196eaffa4da927 Mon Sep 17 00:00:00 2001 From: imurluck <1289042324@qq.com> Date: Mon, 29 Apr 2024 12:54:49 +0000 Subject: [PATCH] ICU-22761 Optimize get value of LocaleObjectCache See #2984 --- .../icu/impl/locale/LocaleObjectCache.java | 36 ++++++++++++------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/icu4j/main/core/src/main/java/com/ibm/icu/impl/locale/LocaleObjectCache.java b/icu4j/main/core/src/main/java/com/ibm/icu/impl/locale/LocaleObjectCache.java index 32049766c2fe..c549d7a62091 100644 --- a/icu4j/main/core/src/main/java/com/ibm/icu/impl/locale/LocaleObjectCache.java +++ b/icu4j/main/core/src/main/java/com/ibm/icu/impl/locale/LocaleObjectCache.java @@ -34,24 +34,34 @@ public V get(K key) { } if (value == null) { key = normalizeKey(key); - V newVal = createObject(key); - if (key == null || newVal == null) { - // subclass must return non-null key/value object + // subclass must return non-null key object + if (key == null) { return null; } - CacheEntry newEntry = new CacheEntry(key, newVal, _queue); + entry = _map.get(key); + if (entry != null) { + value = entry.get(); + } + // hit cache + if (value != null) { + return value; + } - while (value == null) { - cleanStaleEntries(); - entry = _map.putIfAbsent(key, newEntry); - if (entry == null) { - value = newVal; - break; - } else { - value = entry.get(); - } + // if map not contains key or the referent value of CacheEntry is set to be null + // both need create a new value + V newVal = createObject(key); + if (newVal == null) { + // subclass must return non-null value object + return null; } + + CacheEntry newEntry = new CacheEntry(key, newVal, _queue); + // just replace it + _map.put(key, newEntry); + // clean recycled SoftReferences again + cleanStaleEntries(); + return newVal; } return value; }