与普通日期格式化对比,FastDateFormat 为何能线程安全?

FastDateFormat为什么线程安全

SimpleDateFormat的线程不安全

大家都知道SimpleDateFormat是线程不安全的

java 复制代码
protected Calendar calendar;

SimpleDateFormat中的calendar是成员变量,同实例多个线程下会共享该calendar对象

而在进行格式化的时候可能会由于第一个线程还没有格式化完成,而第二个线程已经将时间修改了的情况

java 复制代码
private StringBuffer format(Date date, StringBuffer toAppendTo,
                                FieldDelegate delegate) {
        // 如果第一个线程设置了时间之后还没有格式化为字符串,此时第二个线程将时间覆盖掉,就会出现线程安全问题
        calendar.setTime(date);

        boolean useDateFormatSymbols = useDateFormatSymbols();

        for (int i = 0; i < compiledPattern.length; ) {
            int tag = compiledPattern[i] >>> 8;
            int count = compiledPattern[i++] & 0xff;
            if (count == 255) {
                count = compiledPattern[i++] << 16;
                count |= compiledPattern[i++];
            }

            switch (tag) {
            case TAG_QUOTE_ASCII_CHAR:
                toAppendTo.append((char)count);
                break;

            case TAG_QUOTE_CHARS:
                toAppendTo.append(compiledPattern, i, count);
                i += count;
                break;

            default:
                subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
                break;
            }
        }
        return toAppendTo;
    }

FastDateFormat如何处理的呢

那么FastDateFormat为什么是线程安全的呢?首先FastDateFormat是有一个缓存的,在进行实例化的时候是通过cache缓存来获取实例的

java 复制代码
private static final FormatCache<FastDateFormat> cache= new FormatCache<FastDateFormat>() {
        @Override
        protected FastDateFormat createInstance(final String pattern, final TimeZone timeZone, final Locale locale) {
            return new FastDateFormat(pattern, timeZone, locale);
        }
    };

public static FastDateFormat getInstance(final String pattern) {
    return cache.getInstance(pattern, null, null);
}

将格式化格式、时区和国际化作为一个key存在了cInstanceCache中,cInstanceCache是一个ConcurrentHashMap,相当于相同的格式化格式、时区和国际化会使用同一个FastDateFormat实例

java 复制代码
final MultipartKey key = new MultipartKey(pattern, timeZone, locale);
F format = cInstanceCache.get(key);
if (format == null) {           
    format = createInstance(pattern, timeZone, locale);
    final F previousValue= cInstanceCache.putIfAbsent(key, format);
    if (previousValue != null) {
        // another thread snuck in and did the same work
        // we should return the instance that is in ConcurrentMap
        format= previousValue;              
    }
}

而在使用FastDateFormat进行格式化的时候,是在方法中定义的Calendar局部变量,是不会出现线程安全问题的

java 复制代码
public String format(final Date date) {
    final Calendar c = newCalendar();
    c.setTime(date);
    return applyRulesToString(c);
}

参考文献

相关推荐
badhope16 小时前
Ollama、vLLM、Transformers等本地AI平台终极乱斗:手把手教你选对“高达”驾驶舱,拒绝选择困难症!
react.js·程序员·node.js
慢慢开始吧16 小时前
一套搞定!基于 Docker + Jenkins + Harbor 的国产多系统自动化编译流水线实战全纪录
docker·程序员
SimonKing18 小时前
紧急自查!Apifox被投毒,使用者速看:你的Git、SSH、云密钥可能已泄露
java·后端·程序员
程序员飞哥1 天前
90后大龄程序员失业4个月终于上岸了
后端·面试·程序员
Cyeam1 天前
爆火的 OpenClaw,赢在生态创新
程序员·开源·openai
databook1 天前
别让AI代码,变成明天的技术债
人工智能·程序员·ai编程
NineData1 天前
从业务库到实时分析库,NineData构建MySQL到SelectDB同步链路
数据库·mysql·程序员
掉头发的王富贵2 天前
【2026.3.28深圳腾讯云线下活动分享】我用龙虾3分钟完成了文章的抓取,写作,发布一条龙
程序员·线下活动·腾讯
阿里嘎多学长2 天前
2026-03-27 GitHub 热点项目精选
开发语言·程序员·github·代码托管
我要改名叫嘟嘟2 天前
一个大龄程序员的地铁日记(第8期),给予我影响,帮助我改变的书
程序员