Java日期时间API系列4-----Jdk7及以前的日期时间类的线程安全问题

1.Date类为可变的,在多线程并发环境中会有线程安全问题。

(1)可以使用锁来处理并发问题。

(2)使用JDK8  Instant 替代。

2.Calendar的子类为可变的,在多线程并发环境中会有线程安全问题。

(1)可以使用锁来处理并发问题。

(2)使用JDK8  LocalDateTime 替代。

3.DateFormat和SimpleDateFormat不是线程安全的原因

(1)DateFormat中calendar是共享变量,其子类SimpleDateFormat中也是共享变量。

DateFormat源码:

public abstract class DateFormat extends Format {

/**
* The {@link Calendar} instance used for calculating the date-time fields
* and the instant of time. This field is used for both formatting and
* parsing.
*
* <p>Subclasses should initialize this field to a {@link Calendar}
* appropriate for the {@link Locale} associated with this
* <code>DateFormat</code>.
* @serial
*/
protected Calendar calendar;

(2)SimpleDateFormat format方法源码:

    private StringBuffer format(Date date, StringBuffer toAppendTo,
                                FieldDelegate delegate) {
        // Convert input date to time field list
        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;
    }

  当多个线程同时使用相同的 SimpleDateFormat 对象【如用static修饰的 SimpleDateFormat 】调用format方法时,多个线程会同时调用 calendar.setTime 方法,可能一个线程刚设置好 time 值另外的一个线程马上把设置的 time 值给修改了导致返回的格式化时间可能是错误的。

4.SimpleDateFormat线程安全使用。

(1)使用ThreadLocal处理static方法

    public static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };
System.out.println(df.get().format(new Date()));
2019-12-14

(2)使用JDK8  DateTimeFormatter 替代。

参考:https://www.cnblogs.com/wupeixuan/p/11511915.html?utm_source=gold_browser_extension

  《阿里巴巴Java开发手册》

原文地址:https://www.cnblogs.com/xkzhangsanx/p/12037915.html

时间: 2024-08-10 21:50:33

Java日期时间API系列4-----Jdk7及以前的日期时间类的线程安全问题的相关文章

Java日期时间API系列11-----Jdk8中java.time包中的新的日期时间API类,使用java8日期时间API重写农历LunarDate

通过Java日期时间API系列7-----Jdk8中java.time包中的新的日期时间API类的优点,java8具有很多优点,现在网上查到的农历转换工具类都是基于jdk7及以前的类写的,下面使用java新的日期时间API重写农历LunarDate. package com.xkzhangsan.time; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import ja

Java日期时间API系列8-----Jdk8中java.time包中的新的日期时间API类的LocalDate源码分析

目录 0.前言 1.TemporalAccessor源码 2.Temporal源码 3.TemporalAdjuster源码 4.ChronoLocalDate源码 5.LocalDate源码 6.总结 0.前言 通过前面Java日期时间API系列6-----Jdk8中java.time包中的新的日期时间API类中主要的类关系简图如下: 可以看出主要的LocalDate, LocalTime, LocalDateTime, Instant都是实现相同的接口,这里以LocalDate为例分析jav

Java日期时间API系列17-----Jdk8中java.time包中的新的日期时间API类,java日期计算4,2个日期对比,获取相差年月日部分属性和相差总的天时分秒毫秒纳秒等

通过Java日期时间API系列9-----Jdk8中java.time包中的新的日期时间API类的Period和Duration的区别 ,可以看出java8设计非常好,新增了Period和Duration类,专用于对比2个时间场景: Period,可以获取2个时间相差的年月日的属性. Duration,可以获取2个时间相差总的天时分秒毫秒纳秒. 下面应用: /** * 获取2个日期的相差年月天的年数部分 * @param startInclusive * @param endExclusive

Java日期时间API系列20-----Jdk8中java.time包中的新的日期时间API类,ZoneId时区ID大全等。

Java日期时间API系列19-----Jdk8中java.time包中的新的日期时间API类,ZonedDateTime与ZoneId和LocalDateTime的关系,ZonedDateTime格式化和时区转换等.中已经对ZoneId说明,并列出了常用时区ID信息. 并且通过 java.time.ZoneId.getAvailableZoneIds()获取到所有可用时区ID. 1.测试代码 /** * 获取可用时区ID */ @Test public void getAvailableZon

Java日期时间API系列19-----Jdk8中java.time包中的新的日期时间API类,ZonedDateTime与ZoneId和LocalDateTime的关系,ZonedDateTime格式化和时区转换等。

通过Java日期时间API系列6-----Jdk8中java.time包中的新的日期时间API类中时间范围示意图:可以很清晰的看出ZonedDateTime相当于LocalDateTime+ZoneId. ZonedDateTime是用来处理时区相关的时间,它的各种计算都离不开ZoneId.先看ZoneId. 1. ZoneId 为时区ID,比如Europe/Paris,表示欧洲巴黎时区 1.1 时区相关知识,时区,UTC时间,GMT时间,Unix时间戳 时区 地球自西向东旋转,东边比西边先看到

SQL Server时间粒度系列----第4节季、年时间粒度详解

本文目录列表: 1.SQL Server季时间粒度2.SQL Server年时间粒度 3.总结语 4.参考清单列表 SQL Serve季时间粒度   季时间粒度也即是季度时间粒度.一年每3个月是一个季,一年共4季,1月到3月是第1季.4月到6月是第2个季.依次顺延.季也是日期时间范围的,我们也会引入季基准日期,也就是每个季度的第一天.以下提供季基准日期和整数相互转换的功能的实现,还有获取指定日期时间所在当前年内的季索引,从1开始计数,包括1.2.3.4. 提供季基准日期和整数相互转换的功能函数,

Java日期时间API系列13-----Jdk8中java.time包中的新的日期时间API类,时间类转换,Date转LocalDateTime,LocalDateTime转Date

从前面的系列博客中可以看出Jdk8中java.time包中的新的日期时间API类设计的很好,但Date由于使用仍非常广泛,这就涉及到Date转LocalDateTime,LocalDateTime转Date.下面是时间类互相转换大全,包含Instant.LocalDate.LocalDateTime.LocalTime和Date的相互转换,下面是一个工具类,仅供参考: package com.xkzhangsan.time.converter; import java.time.Instant;

Java日期时间API系列7-----Jdk8中java.time包中的新的日期时间API类的特点

1.不变性 新的日期/时间API中,所有的类都是不可变的,这对多线程环境有好处. 比如:LocalDateTime 2.关注点分离 新的API将人可读的日期时间和机器时间(unix timestamp)明确分离,它为日期(Date).时间(Time).日期时间(DateTime).时间戳(unix timestamp)以及时区定义了不同的类. 不同时间分解成了各个类,比如:LocalDate, LocalTime, LocalDateTime, Instant,Year,Month,YearMo

SQL Server时间粒度系列----第2节日期、周时间粒度详解

本文目录列表: 1.从MySQL提供的TO_DAYS和FROM_DAYS这对函数说起2.SQL Server日期时间粒度3.SQL Server周有关时间粒度 4.总结语 5.参考清单列表 从MySQL提供的TO_DAYS和FROM_DAYS针对函数说起      学习和使用过MySQL的博友,大都知道MySQL提供了很多针对日期和时间的函数,提供了获取不同时间粒度上的功能.相对而然SQL Server提供的有关日期和时间函数不太多的,但是其提供的功能也是蛮强大的.还是让我们继续话说MySQL的