If I create a single instance of a Comparator, can that instance be used across multiple threads to sort collections using Collections.sort()? Or, do I need to create a new instance of the Comparator for each call to Collections.sort() to ensure thread safety?
Share
That depends entirely on how you implement the
Comparator. If, for example, it has instance variables that are written to or whose contents are changed implicitly during comparison, it would not be threadsafe.Most
Comparatorimplementations do no such thing, but one scenario that might reasonably occur is using aSimpleDateFormatto compare Strings that represent dates. Unfortunately,SimpleDateFormatitself is not thread safe.