我是否只能创建一个DateTimeFormatter的静态实例 [英] Can I create only one static instance of DateTimeFormatter

查看:116
本文介绍了我是否只能创建一个DateTimeFormatter的静态实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以只创建一个 DateTimeFormatter 的静态实例,并在项目的任何地方使用它,而不是多次创建它?

Is it possible to create only one static instance of DateTimeFormatter and use it everywhere in my project, instead of creating it multiple times?

public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

在这种情况下是否会出现线程安全问题?

Can there be thread-safety issues in such cases?

推荐答案

是的,这是可能的。您的变量是线程安全的,因为它是不可变的 - 没有其他线程可以更改它。其他解决方案也可以在您的特定情况下使用,但我总是支持不可变对象。

Yes, it is possible. Your variable is Thread Safe because it is immutable - No other thread can change it. Other solutions are also possible in your specific case, but I am always in favour of immutable objects.

参见 Java Concurrency in practice 第3章顺便说一句,这一章似乎可以自由浏览,所以看看吧。

See Java Concurrency in practice Chapter 3. By the way, the chapter seems to be free to browse now, so have a look.

这篇关于我是否只能创建一个DateTimeFormatter的静态实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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