当前位置:网站首页>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 .
边栏推荐
- regular expression
- Idea configures the service (run dashboard) service, and multiple modules are started at the same time
- 框架一步一步方便使用的流程
- ResNet结构对比
- [singleton mode] thread safety of lazy mode
- About localdatetime in swagger
- openjudge:石头剪刀布
- 论文模型主图范例
- The Monte Carlo method solves the PI and draws points with turtle, and completes the progress bar problem
- 冶金物理化学复习 --- 液 - 液相反应动力学
猜你喜欢

Long和Integer如何进行比较,为什么报错

JUC notes

restFul接口使用个人总结

BigDecimal rounds and retains two decimal places

regular expression

Invalid bound statement (not found): com.exam.mapper.UserMapper.findbyid

visio如何快速生成相同的图案,生成图像矩阵

Using Navicat or PLSQL to export CSV format, more than 15 digits will become 000 (e+19) later

论文模型主图范例

Edge calculation kubeedge+edgemash
随机推荐
JVM notes 3: class loading and bytecode Technology
restFul接口使用个人总结
Using Navicat or PLSQL to export CSV format, more than 15 digits will become 000 (e+19) later
Custom JSON return data
冶金物理化学复习 ---- 气固反应动力学
pytorch 计算模型的GFlops和total params的方法
Export excel, generate multiple sheet pages, and name them
You must configure either the server or JDBC driver (via the ‘serverTimezone)
SSM project quick build project configuration file
论文写作用词
24小时内的时间段无交叉
Arrangement of main drawings of the latest 54 papers of eccv22
The essence of dynamic convolution
Openjudge: count the number of numeric characters
冶金物理化学复习 --- 化学反应动力学基础
Redis' bloom filter
openjudge:字符串最大跨距
自定义Json返回数据
数据库面试
The difference between get and post