当前位置:网站首页>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 .
边栏推荐
猜你喜欢

Writing methods of scientific research papers: add analysis and discussion in the method part to explain their contributions and differences

visio如何精确控制图形的大小和位置及角度

Example of main diagram of paper model

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

Thesis writing function words

Digital twin solutions inject new momentum into the construction of chemical parks

框架一步一步方便使用的流程

VMware Workstation 与 Device/Credential Guard 不兼容。禁用 Device/Credential Guard

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

How Visio accurately controls the size, position and angle of graphics
随机推荐
Solve the problem that Oracle cannot use more than 1000 in statements
顺序表oj之删除特定的元素
There is no crossover in the time period within 24 hours
Openjudge: perpetual calendar
2021csdn blog star selection, mutual investment
冶金物理化学复习 --- 化学反应动力学基础
When SQL queries the list, the data is inconsistent twice, and limit is automatically added
The Monte Carlo method solves the PI and draws points with turtle, and completes the progress bar problem
You must configure either the server or JDBC driver (via the ‘serverTimezone)
repackag failed: Unable to find main class
深度学习热力图可视化的方式
openjudge:找第一个只出现一次的字符
docker 部署 mysql5.7.35
低照度图像数据集
论文模型主图范例
顺序表oj之合并两个有序数组
[singleton mode] thread safety of lazy mode
CentOS7安装MySQL5.7
冶金物理化学复习 --- 气-液相反应动力学
Custom JSON return data