gpt4 book ai didi

java - 有没有好的线程安全格式缓存库?

转载 作者:行者123 更新时间:2023-12-04 17:28:32 24 4
gpt4 key购买 nike

我想在我的 webapp 中进行一些格式化,使用 MessageFormat、DateFormat、DecimalFormat 等。

由于这些不是线程安全的,因此每次使用一个静态实例将不起作用,但每次需要创建一个新的 XXXXFormat 对象似乎很浪费。使用 ThreadLocal 缓存和重用它们似乎是一种明显的优化。

这似乎是一种非常常见的模式,所以我想知道是否有任何合适的库。

而不是调用:

    DecimalFormat formatter = new DecimalFormat("###,##0.00");

String formatted = formatter.format(value);

每次我需要格式化某些东西时,为什么不:
    String formatted = FormatCache.formatDecimal("###,##0.00",numberValue);

FormatCache 会在哪里使用以格式模式为键的 HashMap 进行 ThreadLocal 缓存?

大概还有其他方法,例如:
    String FormatCache.formatDecimal(String, Number);
String FormatCache.formatDate(String, Date);
String FormatCache.formatMessage(String, Object...);

最佳答案

Apache Commons Lang FastDateFormat ,它以正确的方式(在我看来)解决了问题,首先是线程安全的:

FastDateFormat is a fast and thread-safe version of SimpleDateFormat.

This class can be used as a direct replacement to SimpleDateFormat in most formatting situations. This class is especially useful in multi-threaded server environments. SimpleDateFormat is not thread-safe in any JDK version, nor will it be as Sun have closed the bug/RFE.

关于java - 有没有好的线程安全格式缓存库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11802205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com