views:

159

answers:

3

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?

A: 

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.

Affe
A: 

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.

Artefacto
It's reasonable that he might be using some resource inside the compare method that's not thread safe. An unsynchronized collection, a calendar, etc. edit: what Michael B said ^
Affe
You're right, I hadn't contemplated those cases.
Artefacto
+4  A: 

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.

Michael Borgwardt