当前位置:网站首页>Simpledateformat thread unsafe and datetimeformatter thread safe
Simpledateformat thread unsafe and datetimeformatter thread safe
2022-07-28 05:41:00 【Little madman green】
1.SimpleDateFormat Thread unsafe
Unsafe output time
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++];
}
public abstract class DateFormat extends Format {
protected Calendar calendar;
public class SimpleDateFormat extends DateFormat
It can be seen that calendar When multiple threads access, there will be unsafe situations , because calendar The value may be changed .
The output format thread is unsafe
Look again SimpleDateFormat Constructor
public SimpleDateFormat(String pattern, Locale locale)
{
if (pattern == null || locale == null) {
throw new NullPointerException();
}
initializeCalendar(locale);
this.pattern = pattern;
this.formatData = DateFormatSymbols.getInstanceRef(locale);
this.locale = locale;
initialize(locale);
}
track pattern Find out pattern Values can be modified
public void applyLocalizedPattern(String pattern) {
String p = translatePattern(pattern,
formatData.getLocalPatternChars(),
DateFormatSymbols.patternChars);
compiledPattern = compile(p);
this.pattern = p;
}
The test sample :
public static void main(String[] args){
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date=new Date();
System.out.println(df.format(date));
df.applyLocalizedPattern("G");
System.out.println(df.format(date));
}
test result :
2022-07-05 09:35:30
A.D.
Sample code to ensure time safety :
public static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
public static void main(String[] args) {
synchronized (df){
Date date = new Date();
System.out.println(df.format(date));
}
}
however final Modification can still be changed pattern .
2.DateTimeFormatter Thread safety
All variables, including himself, are used final Embellished .
public final class DateTimeFormatter {
/** * The printer and/or parser to use, not null. */
private final CompositePrinterParser printerParser;
/** * The locale to use for formatting, not null. */
private final Locale locale;
/** * The symbols to use for formatting, not null. */
private final DecimalStyle decimalStyle;
/** * The resolver style to use, not null. */
private final ResolverStyle resolverStyle;
/** * The fields to use in resolving, null for all fields. */
private final Set<TemporalField> resolverFields;
/** * The chronology to use for formatting, null for no override. */
private final Chronology chrono;
/** * The zone to use for formatting, null for no override. */
private final ZoneId zone;
Use samples :
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
String str1 = dateTimeFormatter.format(LocalDateTime.now());
System.out.println(str1);
String dateStr= "2018 year 12 month 18 Japan ";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy year MM month dd Japan ");
LocalDate date2= LocalDate.parse(dateStr, formatter);
dateTimeFormatter.parse(str1);
Check the source code according to , It does not involve the modification of its own properties or methods , You can think of it as just a method call ,
public void formatTo(TemporalAccessor temporal, Appendable appendable) {
Objects.requireNonNull(temporal, "temporal");
Objects.requireNonNull(appendable, "appendable");
try {
DateTimePrintContext context = new DateTimePrintContext(temporal, this);
if (appendable instanceof StringBuilder) {
printerParser.format(context, (StringBuilder) appendable);
} else {
// buffer output to avoid writing to appendable in case of error
StringBuilder buf = new StringBuilder(32);
printerParser.format(context, buf);
appendable.append(buf);
}
} catch (IOException ex) {
throw new DateTimeException(ex.getMessage(), ex);
}
}
printerParser The members are final modification ,printerParser.format The method code is as follows , Where the member attribute optional It's also final modification ,
public boolean format(DateTimePrintContext context, StringBuilder buf) {
int length = buf.length();
if (optional) {
context.startOptional();
}
try {
for (DateTimePrinterParser pp : printerParsers) {
if (pp.format(context, buf) == false) {
buf.setLength(length); // reset buffer
return true;
}
}
} finally {
if (optional) {
context.endOptional();
}
}
return true;
}
Discovery by query parse So it is with .
边栏推荐
- 【单例模式】懒汉模式的线程安全问题
- Arrangement of main drawings of the latest 54 papers of eccv22
- (dark horse) MySQL beginner advanced notes (blogger lazy dog)
- shell运行原理
- GET与POST区别
- 日期类及其基本功能的实现
- Using Navicat or PLSQL to export CSV format, more than 15 digits will become 000 (e+19) later
- 【idea插件神器】教你如何使用IDEA一键set实体类中所有属性
- Redis' bloom filter
- VMware Workstation 与 Device/Credential Guard 不兼容。禁用 Device/Credential Guard
猜你喜欢

BigDecimal 进行四舍五入 四舍六入和保留两位小数
![[idea plug-in artifact] teaches you how to set all attributes in an entity class with one click of idea](/img/d6/4e69480c5ad5040ee48941ca0fcb37.png)
[idea plug-in artifact] teaches you how to set all attributes in an entity class with one click of idea

冶金物理化学复习 --- 化学反应动力学基础

How Visio accurately controls the size, position and angle of graphics

冶金物理化学复习 --- 气-液相反应动力学

ByteBuffer.position 抛出异常 IllegalArgumentException

Redis' bloom filter

Arrangement of main drawings of the latest 54 papers of eccv22

论文模型主图范例

IDEA配置 service(Run Dashboard) 服务,多模块同时启动
随机推荐
关于swagger中的localDateTime
openjudge:过滤多余的空格
24小时内的时间段无交叉
repackag failed: Unable to find main class
mysql 为查询结果增加序号
冶金物理化学复习 --- 化学反应动力学基础
openjudge:矩阵乘法
Problems encountered when the registry service Eureka switches to nocas
日期类及其基本功能的实现
latex使用\hl进行高亮时遇到引用总是报错,显示少了括号或者多了括号
Long和Integer如何进行比较,为什么报错
Operation and use of collection framework
openjudge:校园食宿预订系统
Digital twin solutions inject new momentum into the construction of chemical parks
Edge calculation kubeedge+edgemash
Digital twin technology creates visual application of smart mine
Openjudge: stone scissors cloth
低照度图像数据集
openjudge:石头剪刀布
mysql中使用list作为参数进行查询