与普通日期格式化对比,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);
}

参考文献

相关推荐
redreamSo10 小时前
AI Daily | AI日报:马斯克Grok 4跑分泄露,有望改写LLM格局; 猫猫话术让大模型数学答错率翻3倍; 安克创新All in AI,代码采纳率破50%
程序员·aigc·资讯
盖世英雄酱581361 天前
容易被程序员忽略的硬件设备
程序员
DeepSeek-大模型系统教程1 天前
深入金融与多模态场景实战:金融文档分块技术与案例汇总
人工智能·ai·语言模型·程序员·大模型·大模型学习·大模型教程
程序员鱼皮1 天前
Cursor 网页版来了,这下拉屎时也能工作了
计算机·ai·程序员·开发·项目·编程经验
redreamSo1 天前
AI Daily | AI日报:Nature:超14%生物医学论文或由AI代写; Grok 4测试成绩优异,数据真实性引争议; 李飞飞:攻克空间智能,为AGI补拼图
程序员·aigc·资讯
老周聊大模型1 天前
《ChatGLM/Llama调优实战:从指令微调到RLHF的工业级对齐方案》
人工智能·程序员·架构
AI大模型2 天前
LangGraph官方文档笔记(6)——时间旅行
程序员·langchain·llm
马可奥勒留2 天前
睡前幻想——基于透明化黄金锚定的超主权货币体系设计:一种解决政府货币滥用的奥地利学派方案(3)
程序员
程序员的小马甲2 天前
如何编写AI提示词
人工智能·程序员·产品经理