SimpleDateFormat为什么是线程不安全的?

这篇具有很好参考价值的文章主要介绍了SimpleDateFormat为什么是线程不安全的?。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

SimpleDateFormat为什么是线程不安全的?,搬砖工逆袭Java架构师,java,数据库,性能优化,网络

大家好,我是哪吒。

在日常开发中,Date工具类使用频率相对较高,大家通常都会这样写:

public static Date getData(String date) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return sdf.parse(date);
}

public static Date getDataByFormat(String date, String format) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    return sdf.parse(date);
}

这很简单啊,有什么争议吗?

你应该听过“时区”这个名词,大家也都知道,相同时刻不同时区的时间是不一样的。

因此在使用时间时,一定要给出时区信息。

public static void getDataByZone(String param, String format) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat(format);

    // 默认时区解析时间表示
    Date date = sdf.parse(param);
    System.out.println(date + ":" + date.getTime());

    // 东京时区解析时间表示
    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));
    Date newYorkDate = sdf.parse(param);
    System.out.println(newYorkDate + ":" + newYorkDate.getTime());
}

public static void main(String[] args) throws ParseException {
   getDataByZone("2023-11-10 10:00:00","yyyy-MM-dd HH:mm:ss");
}

对于当前的上海时区和纽约时区,转化为 UTC 时间戳是不同的时间。

对于同一个本地时间的表示,不同时区的人解析得到的 UTC 时间一定是不同的,反过来不同的本地时间可能对应同一个 UTC。

SimpleDateFormat为什么是线程不安全的?,搬砖工逆袭Java架构师,java,数据库,性能优化,网络

格式化后出现的时间错乱。

public static void getDataByZoneFormat(String param, String format) throws ParseException {
   SimpleDateFormat sdf = new SimpleDateFormat(format);
    Date date = sdf.parse(param);
    // 默认时区格式化输出
    System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss Z]").format(date));
    // 东京时区格式化输出
    TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo"));
    System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss Z]").format(date));
}

public static void main(String[] args) throws ParseException {
   getDataByZoneFormat("2023-11-10 10:00:00","yyyy-MM-dd HH:mm:ss");
}

我当前时区的 Offset(时差)是 +8 小时,对于 +9 小时的纽约,整整差了1个小时,北京早上 10 点对应早上东京 11 点。

SimpleDateFormat为什么是线程不安全的?,搬砖工逆袭Java架构师,java,数据库,性能优化,网络

看看Java 8是如何解决时区问题的:

Java 8 推出了新的时间日期类 ZoneId、ZoneOffset、LocalDateTime、ZonedDateTime 和 DateTimeFormatter,处理时区问题更简单清晰。

public static void getDataByZoneFormat8(String param, String format) throws ParseException {
    ZoneId zone = ZoneId.of("Asia/Shanghai");
    ZoneId tokyoZone = ZoneId.of("Asia/Tokyo");
    ZoneId timeZone = ZoneOffset.ofHours(2);

    // 格式化器
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
    ZonedDateTime date = ZonedDateTime.of(LocalDateTime.parse(param, dtf), zone);

    // withZone设置时区
    DateTimeFormatter dtfz = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss Z");
    System.out.println(dtfz.withZone(zone).format(date));
    System.out.println(dtfz.withZone(tokyoZone).format(date));
    System.out.println(dtfz.withZone(timeZone).format(date));
}

public static void main(String[] args) throws ParseException {
    getDataByZoneFormat8("2023-11-10 10:00:00","yyyy-MM-dd HH:mm:ss");
}
  • Asia/Shanghai对应+8,对应2023-11-10 10:00:00;
  • Asia/Tokyo对应+9,对应2023-11-10 11:00:00;
  • timeZone 是+2,所以对应2023-11-10 04:00:00;

SimpleDateFormat为什么是线程不安全的?,搬砖工逆袭Java架构师,java,数据库,性能优化,网络

在处理带时区的国际化时间问题,推荐使用jdk8的日期时间类:

  1. 通过ZoneId,定义时区;
  2. 使用ZonedDateTime保存时间;
  3. 通过withZone对DateTimeFormatter设置时区;
  4. 进行时间格式化得到本地时间;

思路比较清晰,不容易出错。

在与前端联调时,报了个错,java.lang.NumberFormatException: multiple points,起初我以为是时间格式传的不对,仔细一看,不对啊。

百度一下,才知道是高并发情况下SimpleDateFormat有线程安全的问题。

下面通过模拟高并发,把这个问题复现一下:

public static void getDataByThread(String param, String format) throws InterruptedException {
    ExecutorService threadPool = Executors.newFixedThreadPool(5);
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    // 模拟并发环境,开启5个并发线程
    for (int i = 0; i < 5; i++) {
        threadPool.execute(() -> {
            for (int j = 0; j < 2; j++) {
                try {
                    System.out.println(sdf.parse(param));
                } catch (ParseException e) {
                    System.out.println(e);
                }
            }
        });
    }
    threadPool.shutdown();

    threadPool.awaitTermination(1, TimeUnit.HOURS);
}

果不其然,报错。还将2023年转换成2220年,我勒个乖乖。

在时间工具类里,时间格式化,我都是这样弄的啊,没问题啊,为啥这个不行?原来是因为共用了同一个SimpleDateFormat,在工具类里,一个线程一个SimpleDateFormat,当然没问题啦!

SimpleDateFormat为什么是线程不安全的?,搬砖工逆袭Java架构师,java,数据库,性能优化,网络

可以通过TreadLocal 局部变量,解决SimpleDateFormat的线程安全问题。

public static void getDataByThreadLocal(String time, String format) throws InterruptedException {
    ExecutorService threadPool = Executors.newFixedThreadPool(5);

    ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat(format);
        }
    };

    // 模拟并发环境,开启5个并发线程
    for (int i = 0; i < 5; i++) {
        threadPool.execute(() -> {
            for (int j = 0; j < 2; j++) {
                try {
                    System.out.println(sdf.get().parse(time));
                } catch (ParseException e) {
                    System.out.println(e);
                }
            }
        });
    }
    threadPool.shutdown();

    threadPool.awaitTermination(1, TimeUnit.HOURS);
}

SimpleDateFormat为什么是线程不安全的?,搬砖工逆袭Java架构师,java,数据库,性能优化,网络

看一下SimpleDateFormat.parse的源码:

public class SimpleDateFormat extends DateFormat {
	@Override
	public Date parse(String text, ParsePosition pos){
		CalendarBuilder calb = new CalendarBuilder();
		
		Date parsedDate;
		try {
		    parsedDate = calb.establish(calendar).getTime();
		    // If the year value is ambiguous,
		    // then the two-digit year == the default start year
		    if (ambiguousYear[0]) {
		        if (parsedDate.before(defaultCenturyStart)) {
		            parsedDate = calb.addYear(100).establish(calendar).getTime();
		        }
		    }
		}
	}
}

class CalendarBuilder {
	Calendar establish(Calendar cal) {
	    boolean weekDate = isSet(WEEK_YEAR)
	                        && field[WEEK_YEAR] > field[YEAR];
	    if (weekDate && !cal.isWeekDateSupported()) {
	        // Use YEAR instead
	        if (!isSet(YEAR)) {
	            set(YEAR, field[MAX_FIELD + WEEK_YEAR]);
	        }
	        weekDate = false;
	    }
	
	    cal.clear();
	    // Set the fields from the min stamp to the max stamp so that
	    // the field resolution works in the Calendar.
	    for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {
	        for (int index = 0; index <= maxFieldIndex; index++) {
	            if (field[index] == stamp) {
	                cal.set(index, field[MAX_FIELD + index]);
	                break;
	            }
	        }
	    }
		...
	
	}
}
  1. 先new CalendarBuilder();
  2. 通过parsedDate = calb.establish(calendar).getTime();解析时间;
  3. establish方法内先cal.clear(),再重新构建cal,整个操作没有加锁;

上面几步就会导致在高并发场景下,线程1正在操作一个Calendar,此时线程2又来了。线程1还没来得及处理 Calendar 就被线程2清空了。

因此,通过编写Date工具类,一个线程一个SimpleDateFormat,还是有一定道理的。


🏆哪吒多年工作总结:Java学习路线总结,搬砖工逆袭Java架构师

华为OD机试 2023B卷题库疯狂收录中,刷题点这里

刷的越多,抽中的概率越大,每一题都有详细的答题思路、详细的代码注释、样例测试,发现新题目,随时更新,全天CSDN在线答疑。文章来源地址https://www.toymoban.com/news/detail-831025.html

到了这里,关于SimpleDateFormat为什么是线程不安全的?的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java基础:为什么hashmap是线程不安全的?

    HashMap 是线程不安全的主要原因是它的内部结构和操作不是线程安全的。下面是一些导致 HashMap 线程不安全的因素: 非同步操作:HashMap 的操作不是线程同步的,也就是说,在多线程环境下同时对 HashMap 进行读写操作可能会导致数据不一致的问题。 非原子操作:HashMap 的操作

    2024年02月10日
    浏览(30)
  • 再谈StringBuilder为什么线程不安全以及带来的问题

    比较有意思的是,学习锁消除的过程中,有人讲到StringBuffer在方法内构建,不会被其他方法引用时,StringBuffer的锁会被消除, 于是,顺便看了一下同源的StringBuidler为什么线程不安全,以及为什么多线程不安全,和带来的问题, 有了这篇文章,分享出来,帮助读者轻松应对知

    2024年02月11日
    浏览(31)
  • 面试官问 : ArrayList 不是线程安全的,为什么 ?(看完这篇,以后反问面试官)

    金三银四 ? 也许,但是。 近日,又收到金三银四一线作战小队成员反馈的战况 : 我不管你从哪里看的面经,但是我不允许你看到我这篇文章之后,还不清楚这个面试问题。 本篇内容预告:   ArrayList 是线程不安全的, 为什么 ? ① 结合代码去探一探所谓的不安全  ② 我们

    2024年02月02日
    浏览(47)
  • Java面试题:SimpleDateFormat是线程安全的吗?使用时应该注意什么?

    在Java开发中,我们经常需要获取和处理时间,这需要使用到各种不同的方法。其中,使用SimpleDateFormat类来格式化时间是一种常见的方法。虽然这个类看上去功能比较简单,但是如果使用不当,也可能会引发一些问题。 首先我们要明确一点, SimpleDateFormat不是线程安全的 。

    2024年04月26日
    浏览(26)
  • 什么是线程?为什么需要线程?和进程的区别?

    目录 前言 一.线程是什么? 1.1.为什么需要线程 1.2线程的概念 1.3线程和进程的区别  二.线程的生命周期 三.认识多线程 总结 🎁个人主页:tq02的博客_CSDN博客-C语言,Java,Java数据结构领域博主 🎥 本文由 tq02 原创,首发于 CSDN🙉 🎄 本章讲解内容: 线程的讲解 🎥学习专栏:

    2024年02月14日
    浏览(60)
  • 为什么要使用线程池

    线程池主要是 控制运行的线程的数量 ,处理过程中将任务放入队列,然后在线程创建后启动这些任务,如果线程数量超过了最大数量,超出数量的线程排队等候,等其他线程执行完毕,再从队列中取出任务来执行。 Java线程的 创建 非常昂贵,需要 JVM 和 OS (操作系统)配合

    2023年04月09日
    浏览(44)
  • 为什么使用线程池?解释下线程池参数?

    (1)降低资源消耗:提高线程利用率,降低创建和销毁线程的消耗。 (2)提高响应速度:任务来了,直接有线程可用可执行,而不是线创建线程再执行。 (3)提高线程的可管理性;线程是稀缺资源,使用线程池可以统一分配调优监控。 (1)corePoolSize:代表核心线程数,也

    2024年02月16日
    浏览(38)
  • 为什么要用线程池?

    线程池是一种管理和复用线程资源的机制,它由一个线程池管理器和一组工作线程组成。线程池管理器负责创建和销毁线程池,以及管理线程池中的工作线程。工作线程则负责执行具体的任务。 线程池的主要作用是管理和复用线程资源,避免了线程的频繁创建和销毁所带来的

    2024年02月06日
    浏览(56)
  • js为什么是单线程?

    类比操作系统,多线程问题有: 单一资源多线程抢占,引起死锁问题; 线程间同步数据问题; 为了简单: 更简单的dom渲染。js可以操控dom,而一般来说一个网页一份dom文件,多线程操作dom如果多线程修改dom便容易出现各种问题(例如A线程删除一个dom,而B线程在修改此dom容

    2024年02月07日
    浏览(31)
  • C# 线程本地存储 为什么线程间值不一样

    有朋友在微信里面问我,为什么用 ThreadStatic 标记的字段,只有第一个线程拿到了初始值,其他线程都是默认值,让我能不能帮他解答一下,尼玛,我也不是神仙什么都懂,既然问了,那我试着帮他解答一下,也给后面类似疑问的朋友解个惑吧。 为了方便讲述,定义一个 Th

    2024年01月23日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包