Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

SimpleDateFormatはスレッドアンセーフだぞ

More than 1 year has passed since last update.

Javaで日付を扱う際によくつかうSimpleDateFormatですが、このクラスはスレッドセーフじゃない
なにをいまさらと思う人もいるかもしれまへん、悲しいことに最近こいつせいでハマりました・・・。

スレッド乱立してバーバー流してると1950年とかぐちゃぐちゃの日付がくることがあって調べてみたらこういう次第でした

private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

public String getDate() {
    return sdf.format(new Date());
}

これを、

private final String pattern = "yyyy-MM-dd HH:mm:ss";

public String getDate() {
    return new SimpleDateFormat(pattern).format(new Date());
}

こうや

ドーン!

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away