watery
watery

Reputation: 5487

DateFormat: to create a new instance or to call a subclass getInstance() method?

What is the correct way to use a DateFormat subclass? To explicitly instantiate it or to use one of the static methods of its defining class?

Moreover, in the SimpleDateFormat documentation, about synchronization, it states:

Synchronization

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.

So, what's the best approach in single-threaded applications? And in multi-threaded ones? A new instance for each thread, or a common one whose access is synchronized?
In the latter I guess that it would be better to share the pattern and create new instances when needed, but I'd like your suggestions.

Upvotes: 0

Views: 288

Answers (1)

Miguel Prz
Miguel Prz

Reputation: 13792

As a rule of thumb:

  • Single thread: you can reuse your DateFormat instance

  • Mutithread enviroment: create a new instance each time you use it

Upvotes: 1

Related Questions