Access to methods of a static instance by multiple threads
- Let's say I've created a
final static
instance of the classComparatorChain
. - 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 theComparatorChain
instance.
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 l开发者_如何学运维ong 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.compare
method is thread-safe, it sounds like you should be fine. Most comparisons can easily be thread-safe, as they rarely mutate state.
It is fine to use one instance (singleton) as long as:
- you don't store anything in instance fields
- there's no
synchronized
(it will work, but will block and make things slow)
An example of that is java.lang.String.CASE_INSENSITIVE_ORDER
- a static
comparator
After reading source code of ComparatorChain
, I find it's stateful and not thread-safe if multi-Thread access the ComparatorChain
instance.
精彩评论