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?
Class DateTimeFormatter. Formatter for printing and parsing date-time objects. This class provides the main application entry point for printing and parsing and provides common implementations of DateTimeFormatter : Using predefined constants, such as ISO_LOCAL_DATE.
DateTimeFormatter is immutable and thread-safe. DateTimeFormatter formats a date-time using user defined format such as "yyyy-MMM-dd hh:mm:ss" or using predefined constants such as ISO_LOCAL_DATE_TIME. A DateTimeFormatter can be created with desired Locale, Chronology, ZoneId, and DecimalStyle.
format. DateTimeFormatterBuilder Class in Java. DateTimeFormatterBuilder Class is a builder class that is used to create date-time formatters. DateTimeFormatter is used as a Formatter for printing and parsing date-time objects.
DateTimeFormatter fmt = DateTimeFormatter. ofPattern("yyyy-MM-dd'T'HH:mm:ss"); System. out. println(ldt.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With