使用 guava chache 缓存 DateTimeFormatter 对象,限制缓存数量。

dev
ZhouXY108 2024-09-03 15:50:41 +08:00
parent 79aebe4fcc
commit e9c93a273c
1 changed files with 13 additions and 10 deletions

View File

@ -13,14 +13,14 @@ import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.TimeZone; import java.util.TimeZone;
import org.apache.commons.lang3.StringUtils; import javax.annotation.Nonnull;
import com.google.common.base.Preconditions; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import xyz.zhouxy.plusone.commons.collection.SafeConcurrentHashMap;
import xyz.zhouxy.plusone.commons.time.Quarter; import xyz.zhouxy.plusone.commons.time.Quarter;
import xyz.zhouxy.plusone.commons.time.YearQuarter; import xyz.zhouxy.plusone.commons.time.YearQuarter;
import xyz.zhouxy.plusone.commons.collection.MapWrapper;
/** /**
* *
@ -32,11 +32,14 @@ public class DateTimeTools {
/** /**
* *
*/ */
private static final MapWrapper<String, DateTimeFormatter> DATE_TIME_FORMATTER_CACHE = MapWrapper private static final LoadingCache<String, DateTimeFormatter> DATE_TIME_FORMATTER_CACHE = CacheBuilder.newBuilder()
.<String, DateTimeFormatter>wrap(new SafeConcurrentHashMap<>()) .maximumSize(20)
.keyChecker(pattern -> Preconditions.checkArgument(StringUtils.isNotBlank(pattern), "The pattern could not be blank.")) .build(new CacheLoader<String, DateTimeFormatter>() {
.valueChecker(formatter -> Preconditions.checkNotNull(formatter, "The formatter could not be null.")) @Override
.build(); public DateTimeFormatter load(@Nonnull String pattern) throws Exception {
return DateTimeFormatter.ofPattern(pattern);
}
});
/** /**
* *
@ -45,7 +48,7 @@ public class DateTimeTools {
* @return * @return
*/ */
public static DateTimeFormatter getDateTimeFormatter(String pattern) { public static DateTimeFormatter getDateTimeFormatter(String pattern) {
return DATE_TIME_FORMATTER_CACHE.computeIfAbsent(pattern, DateTimeFormatter::ofPattern); return DATE_TIME_FORMATTER_CACHE.getUnchecked(pattern);
} }
/** /**