Java8之前的日期和时间API,存在一些问题,最重要的就是线程安全的问题。这些问题都在Java8中的日期和时间API中得到了解决,而且Java8中的日期和时间API更加强大。

传统时间格式化的线程安全问题

示例:

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*; public class TestOldSimpleDateFormat {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Callable<Date> task = new Callable<Date>() {
@Override
public Date call() throws Exception {
return sdf.parse("2020-01-01");
}
};
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<Date>> list = new ArrayList<>();
for (int i=0;i<10;i++){
Future<Date> future = pool.submit(task);
list.add(future);
}
for (Future<Date> future : list){
System.out.println(future.get());
}      pool.shutdown();
}
}

以上代码运行会报错:

报错缘由:取部分源码解释

    /**
* SimpleDateFormat 类的 parse 方法 部分源码
*/
public Date parse(String source) throws ParseException
{
ParsePosition pos = new ParsePosition(0);
Date result = parse(source, pos);
if (pos.index == 0)
throw new ParseException("Unparseable date: \"" + source + "\"" ,
pos.errorIndex);
return result;
} public Date parse(String text, ParsePosition pos)
{
// 省略上面诸多代码
Date parsedDate; CalendarBuilder calb = new CalendarBuilder();
try {
//这里这个 calendar 对象是 SimpleDateFormat 类的父类 DateFormat 中的属性 : protected Calendar calendar;
parsedDate = calb.establish(calendar).getTime();//这个 calb.establish(calendar) 方法中,这个方法中的主要步骤不是原子操作,并且会对 calendar 对象进行修改,所以在多线程环境下就会出现线程安全问题。
// 省略下面面诸多代码
}
catch (IllegalArgumentException e) {
//省略.........................
return null;
}
return parsedDate;
}
 Calendar establish(Calendar cal) {
boolean weekDate = isSet(WEEK_YEAR)
&& field[WEEK_YEAR] > field[YEAR];
if (weekDate && !cal.isWeekDateSupported()) {
// Use YEAR instead
if (!isSet(YEAR)) {
set(YEAR, field[MAX_FIELD + WEEK_YEAR]);
}
weekDate = false;
} cal.clear();
// Set the fields from the min stamp to the max stamp so that
// the field resolution works in the Calendar.
for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {
for (int index = 0; index <= maxFieldIndex; index++) {
if (field[index] == stamp) {
cal.set(index, field[MAX_FIELD + index]);
break;
}
}
} if (weekDate) {
int weekOfYear = isSet(WEEK_OF_YEAR) ? field[MAX_FIELD + WEEK_OF_YEAR] : 1;
int dayOfWeek = isSet(DAY_OF_WEEK) ?
field[MAX_FIELD + DAY_OF_WEEK] : cal.getFirstDayOfWeek();
if (!isValidDayOfWeek(dayOfWeek) && cal.isLenient()) {
if (dayOfWeek >= 8) {
dayOfWeek--;
weekOfYear += dayOfWeek / 7;
dayOfWeek = (dayOfWeek % 7) + 1;
} else {
while (dayOfWeek <= 0) {
dayOfWeek += 7;
weekOfYear--;
}
}
dayOfWeek = toCalendarDayOfWeek(dayOfWeek);
}
cal.setWeekDate(field[MAX_FIELD + WEEK_YEAR], weekOfYear, dayOfWeek);
}
return cal;
}

综上,我们可以看到 SimpleDateFormat 类中的parse 方法,调用了 CalendarBuilder 的 establish(calendar) 方法,并在方法中,对 calendar 对象进行了各种判断及修改,并且这些操作都不是原子操作或同步操作,而这个calendar 对象又是 SimpleDateFormat 的父类 DateFormat 的一个实例变量,所以,在多线程同时调用SimpleDateFormat 的 parse 方法的时候,就会出现线程安全问题。


针对以上异常,JAVA8之前的解决办法:

1. 将 SimpleDateFormat 对象定义成局部变量。

2. 加锁。

3. 使用ThreadLocal,每个线程都拥有自己的SimpleDateFormat对象副本。

示例(加锁):

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Callable<Date> task = new Callable<Date>() {
@Override
public synchronized Date call() throws Exception {//加个同步,解决问题
return sdf.parse("2020-01-01");
// return DateFormatThreadLocal.convert("2020-01-01");
}
};
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<Date>> list = new ArrayList<>();
for (int i=0;i<10;i++){
Future<Date> future = pool.submit(task);
list.add(future);
}
for (Future<Date> future : list){
System.out.println(future.get());
}
pool.shutdown();

示例(ThreadLocal):

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date; public class DateFormatThreadLocal {
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
public static Date convert(String source) throws Exception {
return df.get().parse(source);
}
} //////////////////////////////////////////////////////////////// public class TestOldSimpleDateFormat {
public static void main(String[] args) throws Exception {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Callable<Date> task = new Callable<Date>() {
@Override
public Date call() throws Exception {
// return sdf.parse("2020-01-01");
return DateFormatThreadLocal.convert("2020-01-01");
}
};
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<Date>> list = new ArrayList<>();
for (int i=0;i<10;i++){
Future<Date> future = pool.submit(task);
list.add(future);
}
for (Future<Date> future : list){
System.out.println(future.get());
}
     pool.shutdown();
} }

JAVA8的解决办法:使用新的API(DateTimeFormatter  和 LocalDate )

示例:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*; public class TestOldSimpleDateFormat {
public static void main(String[] args) throws Exception {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); Callable<LocalDate> task = new Callable<LocalDate>() {
@Override
public LocalDate call() throws Exception {
// return sdf.parse("2020-01-01");
return LocalDate.parse("2020-01-01",formatter);
}
};
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<LocalDate>> list = new ArrayList<>();
for (int i=0;i<10;i++){
Future<LocalDate> future = pool.submit(task);
list.add(future);
}
for (Future<LocalDate> future : list){
System.out.println(future.get());
}
pool.shutdown();
}
}

【JAVA8新的时间与日期 API】- 传统时间格式化的线程安全问题的更多相关文章

  1. 为什么不建议使用Date,而是使用Java8新的时间和日期API?

    Java 8:新的时间和日期API 在Java 8之前,所有关于时间和日期的API都存在各种使用方面的缺陷,因此建议使用新的时间和日期API,分别从旧的时间和日期的API的缺点以及解决方法.Java ...

  2. 【转】Java 8新特性(四):新的时间和日期API

    Java 8另一个新增的重要特性就是引入了新的时间和日期API,它们被包含在java.time包中.借助新的时间和日期API可以以更简洁的方法处理时间和日期. 在介绍本篇文章内容之前,我们先来讨论Ja ...

  3. Java 8新特性(四):新的时间和日期API

    Java 8另一个新增的重要特性就是引入了新的时间和日期API,它们被包含在java.time包中.借助新的时间和日期API可以以更简洁的方法处理时间和日期. 在介绍本篇文章内容之前,我们先来讨论Ja ...

  4. Linux 设置系统时间和日期 API

    嵌入式Linux 设置时间和日期 API ,它是busybox要提取的源代码. Linux设置时间和日期的步骤: 1. 设置系统时间和日期: 2. 该系统的时间和日期,同步到硬件. #include ...

  5. Java8新特性 - 新时间和日期 API

    本地时间和时间戳 主要方法: now:静态方法,根据当前时间创建对象 of:静态方法,根据指定日期/时间创建对象 plusDays,plusWeeks,plusMonths,plusYears:向当前 ...

  6. [转]JavaSE 8—新的时间和日期API

    为什么我们需要一个新的时间日期API Java开发中一直存在一个问题,JDK提供的时间日期API一直对开发者没有提供良好的支持. 比如,已有的的类(如java.util.Date和SimpleDate ...

  7. jdk8-全新时间和日期api

    1.jdk8日期和时间api是线程安全的 1.java.time  处理日期时间 2.java.time.temporal: 时间校正器.获取每个月第一天,周几等等 3.java.time.forma ...

  8. Java8 中的时间和日期 API

    1. 日期和时间概述 LocalDate,LocalTime,LocalDateTime类的实例是不可变的对象,分别表示使用 ISO-8601 日历系统 的日期,时间,日期和时间;它们提供了简单的日期 ...

  9. java8新特性七-Date Time API

    Java 8通过发布新的Date-Time API (JSR 310)来进一步加强对日期与时间的处理. 在旧版的 Java 中,日期时间 API 存在诸多问题,其中有: 非线程安全 − java.ut ...

随机推荐

  1. Matlab矩阵学习三 矩阵的运算

    Matlab矩阵的运算 一.矩阵的加减 在matlab中,矩阵的加减和数的加减符号一样,都是"+"和”-“,不同的是两个进行运算的矩阵维度必须相同  二.数乘  三.乘法 矩阵乘法 ...

  2. jQuery-简单理解

    1.概念 jQuery是js的一个类库,主要封装的是js中DOM操作部分,使用和原生js一样 2.代码展示 HTML部分 封装原理 test测试 JS部分 //声明对象 var bjsxt = {}; ...

  3. Rocket - interrupts - Parameters

    https://mp.weixin.qq.com/s/eD1_hG0n8W2Wodk25N5KnA 简单介绍interrupts相关的Parameters. 1. IntRange 定义一个中断号区间 ...

  4. PowerPC-object与elf中的符号引用

    https://mp.weixin.qq.com/s/6snzjEpDT4uQuCI2Nx9VcQ   一. 符号引用 编译会先把每个源代码文件编译成object目标文件,然后把所有目标文件链接到一起 ...

  5. Rocket - util - MaskGen

    https://mp.weixin.qq.com/s/_aJqf1cFJDK5RVRBhxTWOw   介绍MaskGen的实现.   ​​   1. 基本介绍   给定总线宽度beatBytes,根 ...

  6. jchdl - RTL实例 - AndAnd

    https://mp.weixin.qq.com/s/JhUB3M1WhjAyUrN1HPIPTA   AndAnd是三输入与门模块,输出为相与的结果.   参考链接 https://github.c ...

  7. ASP.NET中IHttpHandler与IHttpModule的区别(带样例说明)

    IHttpModule相对来说,是一个网页的添加 IHttpHandler相对来说,却是网页的替换 先建一个HandlerDemo的类 using System; using System.Colle ...

  8. Java实现 蓝桥杯VIP 算法训练 完数

    问题描述 一个数如果恰好等于它的因子之和,这个数就称为"完数".例如,6的因子为1.2.3,而6=1+2+3,因此6就是"完数".又如,28的因子为1.2.4. ...

  9. java实现购物券消费方案

    公司发了某商店的购物券1000元,限定只能购买店中的m种商品.每种商品的价格分别为m1,m2,-,要求程序列出所有的正好能消费完该购物券的不同购物方法. 程序输入: 第一行是一个整数m,代表可购买的商 ...

  10. Mybatis连接池及事务

    一:Mybatis连接池 我们在学习WEB技术的时候肯定接触过许多连接池,比如C3P0.dbcp.druid,但是我们今天说的mybatis中也有连接池技术,可是它采用的是自己内部实现了一个连接池技术 ...