Can I create only one static instance of DateTimeFormatter

三世轮回 提交于 2019-12-22 06:00:29

问题


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?


回答1:


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.

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



来源:https://stackoverflow.com/questions/48540562/can-i-create-only-one-static-instance-of-datetimeformatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!