Java日期时间API系列4-----Jdk7及以前的日期时间类的线程安全问题
2024-08-29 07:50:15
1.Date类为可变的,在多线程并发环境中会有线程安全问题。
(1)可以使用锁来处理并发问题。
(2)使用JDK8 Instant 或 LocalDateTime替代。
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开发手册》
最新文章
- Extjs5 tree扩展----treepanel树组件
- 【原】jquery图片预览
- (转)关于List中FindAll用法的一些简单示例
- bsp tree
- Letter of application, e-mail version
- Perl入门(四)Perl的正則表達式
- [转]5个JavaScript面试题
- C#,VB.NET如何将Word转换为PDF和Text
- 对clear float 的理解
- PyPI使用国内源
- vue 回到页面顶部
- 第三节:ThreadPool的线程开启、线程等待、线程池的设置、定时功能
- JS——页面带参数跳转
- 008_python内置语法
- Linux下查看文件系统磁盘使用
- 深入理解Java虚拟机(笔记)
- Concordion test
- linux系统centOS7下搭建redis集群中ruby版本过低问题的解决方法
- 安全:CSRF
- Tomcat7环境下面MySQL 56/Oracle数据库连接池的配置
热门文章
- 【algo&;ds】4.B树、字典树、红黑树、跳表
- 小程序底部tapbar
- Glide缓存流程
- ASP.NET Core SignalR:基础概述
- JavaWeb问题记录——在Windows上启动Tomcat后命令行窗口乱码
- IDEA中新建SpringBoot项目时提示:Artifact contains illegal characters
- android笔记--Intent和IntentFilter详解
- .deb 包如何安装到指定目录; Ubuntu; Debian like;
- idea延长使用期
- mysql五大引擎的区别和优劣之分