开发者

In Java, is a Comparator used in Collections.sort() thread safe?

If I create a single instance of a Comparator, can that instance be used across multiple threads to sort collections using Coll开发者_Python百科ections.sort()? Or, do I need to create a new instance of the Comparator for each call to Collections.sort() to ensure thread safety?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜