SimpleDateFormat Not Thread Safe
Format dates safely across threads: SimpleDateFormat instances are not synchronized per javadoc, so build one per call or share an immutable DateTimeFormatter.
Code
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.TimeZone;
public class SharedDateFormat {
// SimpleDateFormat javadoc: "Date formats are not synchronized. It is
// recommended to create separate format instances for each thread."
static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
// 每次调用新建实例:不跨线程共享,无需外部同步
static String safePerCall(Instant instant) {
SimpleDateFormat fmt = new SimpleDateFormat(PATTERN);
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
return fmt.format(Date.from(instant));
}
public static void main(String[] args) {
Instant instant = Instant.parse("2023-11-14T22:13:20Z");
System.out.println(safePerCall(instant));
// DateTimeFormatter 不可变:javadoc 建议它作为 immutable、thread-safe 的替代
DateTimeFormatter shared = DateTimeFormatter.ofPattern(PATTERN).withZone(ZoneOffset.UTC);
System.out.println(shared.format(instant));
}
}Inside the snippet
Under the hood: the class SharedDateFormat and the functions safePerCall and main.
Watch out for
- Copy, run: the standard library answers every call in the file.
Putting it to use
Signature: static String safePerCall(Instant instant)
The sequence safePerCall lives in main; running the file triggers it.
Core lines
return fmt.format(Date.from(instant));
Interactive Tools for This Topic
FAQ
- How do you run SimpleDateFormat Not Thread Safe?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.