From e12af8d6de9f974c014ae8cddcf1b696cfefe1a5 Mon Sep 17 00:00:00 2001 From: Prabhat Sharma Date: Thu, 5 Oct 2023 08:33:39 +0530 Subject: [PATCH] Changed JavaDateTimeFormatter caching of parser from MRU(most recently used) to a simple last used formatter Signed-off-by: Prabhat Sharma --- .../common/time/JavaDateFormatter.java | 42 ++++++------------- 1 file changed, 13 insertions(+), 29 deletions(-) diff --git a/server/src/main/java/org/opensearch/common/time/JavaDateFormatter.java b/server/src/main/java/org/opensearch/common/time/JavaDateFormatter.java index 1adc393d98347..14191357fb8aa 100644 --- a/server/src/main/java/org/opensearch/common/time/JavaDateFormatter.java +++ b/server/src/main/java/org/opensearch/common/time/JavaDateFormatter.java @@ -53,8 +53,6 @@ import java.util.Map; import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.BiConsumer; import java.util.stream.Collectors; @@ -76,7 +74,7 @@ class JavaDateFormatter implements DateFormatter { private final List parsers; private final JavaDateFormatter roundupParser; private final Boolean canCacheLastParsedFormatter; - private final ReadWriteLock parserLock = new ReentrantReadWriteLock(); + private volatile DateTimeFormatter lastParsedformatter = null; /** * A round up formatter @@ -289,36 +287,22 @@ public TemporalAccessor parse(String input) { private TemporalAccessor doParse(String input) { if (parsers.size() > 1) { Object object = null; - DateTimeFormatter lastParsedformatter = null; - parserLock.readLock().lock(); - try { - for (DateTimeFormatter formatter : parsers) { - ParsePosition pos = new ParsePosition(0); - object = formatter.toFormat().parseObject(input, pos); - if (parsingSucceeded(object, input, pos)) { - lastParsedformatter = formatter; - break; - } + if (canCacheLastParsedFormatter && lastParsedformatter != null) { + ParsePosition pos = new ParsePosition(0); + object = lastParsedformatter.toFormat().parseObject(input, pos); + if (parsingSucceeded(object, input, pos)) { + return (TemporalAccessor) object; } - } finally { - parserLock.readLock().unlock(); } - - if (lastParsedformatter != null) { - if (canCacheLastParsedFormatter) { - parserLock.writeLock().lock(); - try { - if (lastParsedformatter != parsers.get(0)) { - parsers.remove(lastParsedformatter); - parsers.add(0, lastParsedformatter); - } - } finally { - parserLock.writeLock().unlock(); - } + for (DateTimeFormatter formatter : parsers) { + ParsePosition pos = new ParsePosition(0); + object = formatter.toFormat().parseObject(input, pos); + if (parsingSucceeded(object, input, pos)) { + lastParsedformatter = formatter; + return (TemporalAccessor) object; } - - return (TemporalAccessor) object; } + throw new DateTimeParseException("Failed to parse with all enclosed parsers", input, 0); } return this.parsers.get(0).parse(input);