问题
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