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?
Comparator is an interface, it has no inherent concurrency properties. It's up to how you write it if your implementation is threadsafe or not. If everything it does is confined to the scope of the compare method (No Instance or Class level state) and all the resources it uses are threadsafe, then it will itself be threadsafe.
I'd very surprised if I found a non-thread safe Comparator, since they're usually (always?) reentrant.
The concurrency problem would be if the collection being sorted was being changed while the sort happened.
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 Comparator
implementations do no such thing, but one scenario that might reasonably occur is using a SimpleDateFormat
to compare Strings that represent dates. Unfortunately, SimpleDateFormat
itself is not thread safe.