- Let’s say I’ve created a
final staticinstance of the class
ComparatorChain. - Through
Collections.sort(List<T> list, Comparator<? super T> c)I’m using this instance. - Somewhere in
Collections.sort(List<T> list, Comparator<? super T> c)Comparator.compare(T o1, T o2)is called on theComparatorChaininstance.
Now my beginners question:
When multiple threads use this static instance can they all call the Comparator.compare(T o1, T o2) method at the same time?
I’d suppose that as long as there is no synchronized modifier involved, they could. Is this right?
Why do I want to know this?
Through such a static instance I could avoid the useless creation of ComparatorChain objects.
Yes, if there’s no synchronization involved, there’s nothing to stop multiple threads calling the same method multiple times concurrently – whether that’s a static method or an instance method on an object which is accessible by multiple threads, however it’s accessible by those threads.
It’s worth noting that although a variable can be static, there’s no such concept as a static object. While on this occasion I knew what you meant, the difference between a variable and an object is often vital.
So long as your
ComparatorChain.comparemethod is thread-safe, it sounds like you should be fine. Most comparisons can easily be thread-safe, as they rarely mutate state.