我们可以将 SimpleDateFormat 对象声明为静态对象吗 [英] Can we declare SimpleDateFormat objects as static objects

查看:40
本文介绍了我们可以将 SimpleDateFormat 对象声明为静态对象吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SimpleDateFormat monthFormat = new SimpleDateFormat("MMMM");SimpleDateFormat fullFormat = new SimpleDateFormat("EE MMM dd, HH:mm:ss")

我有几个这样的代码经常被调用,将它们声明为 static 变量是否有意义?

在这种情况下,将动态参数传递给 format() 方法是否线程安全?

解决方案

它们不是线程安全的.使用 Joda-time 的版本.

或者将它们包装在同步方法中并使其成为线程安全的

Doc 说的很清楚><块引用>

日期格式不同步.它建议单独创建为每个线程格式化实例.如果多线程访问一个格式同时,它必须是同步的外部.

SimpleDateFormat monthFormat = new SimpleDateFormat("MMMM");
SimpleDateFormat fullFormat = new SimpleDateFormat("EE MMM dd, HH:mm:ss")

I have several such piece of code which gets invoked often, would it make sense to declare them as static variables?

Is it thread safe to pass dynamic arguments to the format() method in such cases?

解决方案

No they aren't thread-safe.Use Joda-time's version instead.

Or make them wrapped in synchronized method and make it thread-safe

Doc Says it clearly

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

这篇关于我们可以将 SimpleDateFormat 对象声明为静态对象吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆