java的SimpleDateFormat线程不安全出问题了,虚竹教你多种解决方案

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

String dateString = simpleDateFormat.format(new Date());

try {

Date parseDate = simpleDateFormat.parse(dateString);

String dateString2 = simpleDateFormat.format(parseDate);

System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));

} catch (Exception e) {

System.out.println(Thread.currentThread().getName()+" 格式化失败 ");

}

}

}

}

image-20210805936439

由图可知,已经保证了线程安全,但这种方案不建议在高并发场景下使用,因为会创建大量的SimpleDateFormat对象,影响性能。

解决方案2:加锁:synchronized锁和Lock锁


加synchronized锁

SimpleDateFormat对象还是定义为全局变量,然后需要调用SimpleDateFormat进行格式化时间时,再用synchronized保证线程安全。

public class SimpleDateFormatDemoTest2 {

private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

public static void main(String[] args) {

//1、创建线程池

ExecutorService pool = Executors.newFixedThreadPool(5);

//2、为线程池分配任务

ThreadPoolTest threadPoolTest = new ThreadPoolTest();

for (int i = 0; i < 10; i++) {

pool.submit(threadPoolTest);

}

//3、关闭线程池

pool.shutdown();

}

static class ThreadPoolTest implements Runnable{

@Override

public void run() {

try {

synchronized (simpleDateFormat){

String dateString = simpleDateFormat.format(new Date());

Date parseDate = simpleDateFormat.parse(dateString);

String dateString2 = simpleDateFormat.format(parseDate);

System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));

}

} catch (Exception e) {

System.out.println(Thread.currentThread().getName()+" 格式化失败 ");

}

}

}

}

image-2021080591591

如图所示,线程是安全的。定义了全局变量SimpleDateFormat,减少了创建大量SimpleDateFormat对象的损耗。但是使用synchronized锁,

同一时刻只有一个线程能执行锁住的代码块,在高并发的情况下会影响性能。但这种方案不建议在高并发场景下使用

加Lock锁

加Lock锁和synchronized锁原理是一样的,都是使用锁机制保证线程的安全。

public class SimpleDateFormatDemoTest3 {

private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

private static Lock lock = new ReentrantLock();

public static void main(String[] args) {

//1、创建线程池

ExecutorService pool = Executors.newFixedThreadPool(5);

//2、为线程池分配任务

ThreadPoolTest threadPoolTest = new ThreadPoolTest();

for (int i = 0; i < 10; i++) {

pool.submit(threadPoolTest);

}

//3、关闭线程池

pool.shutdown();

}

static class ThreadPoolTest implements Runnable{

@Override

public void run() {

try {

lock.lock();

String dateString = simpleDateFormat.format(new Date());

Date parseDate = simpleDateFormat.parse(dateString);

String dateString2 = simpleDateFormat.format(parseDate);

System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));

} catch (Exception e) {

System.out.println(Thread.currentThread().getName()+" 格式化失败 ");

}finally {

lock.unlock();

}

}

}

}

image-20210805940496

由结果可知,加Lock锁也能保证线程安全。要注意的是,最后一定要释放锁,代码里在finally里增加了lock.unlock();,保证释放锁。

在高并发的情况下会影响性能。这种方案不建议在高并发场景下使用

解决方案3:使用ThreadLocal方式


使用ThreadLocal保证每一个线程有SimpleDateFormat对象副本。这样就能保证线程的安全。

public class SimpleDateFormatDemoTest4 {

private static ThreadLocal threadLocal = new ThreadLocal(){

@Override

protected DateFormat initialValue() {

return new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

}

};

public static void main(String[] args) {

//1、创建线程池

ExecutorService pool = Executors.newFixedThreadPool(5);

//2、为线程池分配任务

ThreadPoolTest threadPoolTest = new ThreadPoolTest();

for (int i = 0; i < 10; i++) {

pool.submit(threadPoolTest);

}

//3、关闭线程池

pool.shutdown();

}

static class ThreadPoolTest implements Runnable{

@Override

public void run() {

try {

String dateString = threadLocal.get().format(new Date());

Date parseDate = threadLocal.get().parse(dateString);

String dateString2 = threadLocal.get().format(parseDate);

System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));

} catch (Exception e) {

System.out.println(Thread.currentThread().getName()+" 格式化失败 ");

}finally {

//避免内存泄漏,使用完threadLocal后要调用remove方法清除数据

threadLocal.remove();

}

}

}

}

image-202108059729

使用ThreadLocal能保证线程安全,且效率也是挺高的。适合高并发场景使用

解决方案4:使用DateTimeFormatter代替SimpleDateFormat


使用DateTimeFormatter代替SimpleDateFormat(DateTimeFormatter是线程安全的,java 8+支持)

DateTimeFormatter介绍 传送门:万字博文教你搞懂java源码的日期和时间相关用法

public class DateTimeFormatterDemoTest5 {

private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”);

public static void main(String[] args) {

//1、创建线程池

ExecutorService pool = Executors.newFixedThreadPool(5);

//2、为线程池分配任务

ThreadPoolTest threadPoolTest = new ThreadPoolTest();

for (int i = 0; i < 10; i++) {

pool.submit(threadPoolTest);

}

//3、关闭线程池

pool.shutdown();

}

static class ThreadPoolTest implements Runnable{

@Override

public void run() {

try {

String dateString = dateTimeFormatter.format(LocalDateTime.now());

TemporalAccessor temporalAccessor = dateTimeFormatter.parse(dateString);

String dateString2 = dateTimeFormatter.format(temporalAccessor);

System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));

} catch (Exception e) {

e.printStackTrace();

System.out.println(Thread.currentThread().getName()+" 格式化失败 ");

}

}

}

}

image-2021080591443373

使用DateTimeFormatter能保证线程安全,且效率也是挺高的。适合高并发场景使用

解决方案5:使用FastDateFormat 替换SimpleDateFormat


使用FastDateFormat 替换SimpleDateFormat(FastDateFormat 是线程安全的,Apache Commons Lang包支持,不受限于java版本)

public class FastDateFormatDemo6 {

private static FastDateFormat fastDateFormat = FastDateFormat.getInstance(“yyyy-MM-dd HH:mm:ss”);

public static void main(String[] args) {

//1、创建线程池

ExecutorService pool = Executors.newFixedThreadPool(5);

//2、为线程池分配任务

ThreadPoolTest threadPoolTest = new ThreadPoolTest();

for (int i = 0; i < 10; i++) {

pool.submit(threadPoolTest);

}

//3、关闭线程池

pool.shutdown();

}

static class ThreadPoolTest implements Runnable{

@Override

public void run() {

try {

String dateString = fastDateFormat.format(new Date());

Date parseDate = fastDateFormat.parse(dateString);

String dateString2 = fastDateFormat.format(parseDate);

System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));

} catch (Exception e) {

e.printStackTrace();

System.out.println(Thread.currentThread().getName()+" 格式化失败 ");

}

}

}

}

使用FastDateFormat能保证线程安全,且效率也是挺高的。适合高并发场景使用

FastDateFormat源码分析

Apache Commons Lang 3.5

//FastDateFormat@Overridepublic String format(final Date date) { return printer.format(date);} @Override public String format(final Date date) { final Calendar c = Calendar.getInstance(timeZone, locale); c.setTime(date); return applyRulesToString©; }

源码中 Calender 是在 format 方法里创建的,肯定不会出现 setTime 的线程安全问题。这样线程安全疑惑解决了。那还有性能问题要考虑?

我们来看下FastDateFormat是怎么获取的

FastDateFormat.getInstance();FastDateFormat.getInstance(CHINESE_DATE_TIME_PATTERN);

看下对应的源码

/** * 获得 FastDateFormat实例,使用默认格式和地区 * * @return FastDateFormat /public static FastDateFormat getInstance() { return CACHE.getInstance();}/* * 获得 FastDateFormat 实例,使用默认地区
* 支持缓存 * * @param pattern 使用{@link java.text.SimpleDateFormat} 相同的日期格式 * @return FastDateFormat * @throws IllegalArgumentException 日期格式问题 */public static FastDateFormat getInstance(final String pattern) { return CACHE.getInstance(pattern, null, null);}

这里有用到一个CACHE,看来用了缓存,往下看

private static final FormatCache CACHE = new FormatCache(){ @Override protected FastDateFormat createInstance(final String pattern, final TimeZone timeZone, final Locale locale) { return new FastDateFormat(pattern, timeZone, locale); }};//abstract class FormatCache { … private final ConcurrentMap<Tuple, F> cInstanceCache = new ConcurrentHashMap<>(7); private static final ConcurrentMap<Tuple, String> C_DATE_TIME_INSTANCE_CACHE = new ConcurrentHashMap<>(7); …}

image-20210728914309

在getInstance 方法中加了ConcurrentMap 做缓存,提高了性能。且我们知道ConcurrentMap 也是线程安全的。

实践

/**

  • 年月格式 {@link FastDateFormat}:yyyy-MM

*/

public static final FastDateFormat NORM_MONTH_FORMAT = FastDateFormat.getInstance(NORM_MONTH_PATTERN);

image-2021072895013629

//FastDateFormatpublic static FastDateFormat getInstance(final String pattern) { return CACHE.getInstance(pattern, null, null);}

image-20210728205104833

image-2021072895259113

如图可证,是使用了ConcurrentMap 做缓存。且key值是格式,时区和locale(语境)三者都相同为相同的key。

结论

======================================================================

这个是阿里巴巴 java开发手册中的规定:

img

1、不要定义为static变量,使用局部变量

2、加锁:synchronized锁和Lock锁

3、使用ThreadLocal方式

4、使用DateTimeFormatter代替SimpleDateFormat(DateTimeFormatter是线程安全的,java 8+支持)

5、使用FastDateFormat 替换SimpleDateFormat(FastDateFormat 是线程安全的,Apache Commons Lang包支持,java8之前推荐此用法)

推荐相关文章

==========================================================================

hutool日期时间系列文章


1DateUtil(时间工具类)-当前时间和当前时间戳

2DateUtil(时间工具类)-常用的时间类型Date,DateTime,Calendar和TemporalAccessor(LocalDateTime)转换

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

最近我根据上述的技术体系图搜集了几十套腾讯、头条、阿里、美团等公司21年的面试题,把技术点整理成了视频(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
mg-hUIaTqfd-1713497248373)]

[外链图片转存中…(img-aw4tqWJ9-1713497248375)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

[外链图片转存中…(img-r67TnYu7-1713497248377)]

最近我根据上述的技术体系图搜集了几十套腾讯、头条、阿里、美团等公司21年的面试题,把技术点整理成了视频(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,这里以图片的形式给大家展示一部分

[外链图片转存中…(img-iIgB62cP-1713497248378)]

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值