Home > Software engineering >  Why Java is not using VarHandle for collection classes the way it is using it for AtomicReferenceArr
Why Java is not using VarHandle for collection classes the way it is using it for AtomicReferenceArr

Time:12-25

By using VarHandle class in Java you can achieve atomic operations on objects, through which classes like AtomicReferenceArray can perform concurrent operations on elements of array without locking (synchronized) the whole array structure ending up in significant performance gain.

Is there any specific reason why other synchronized and thread safe versions of collections are not implementing such model?
For example all the synchronized factory methods in Collections class return the version of their corresponding collection that uses synchronized methods which locks the whole collection!

CodePudding user response:

Atomic operations on objects don't make a whole collection necessarily thread-safe. The synchronized factory methods in Collections, for example, are the only way to make arbitrary collection implementations thread-safe.

It is possible that VarHandle could be used to optimize collections specifically built for concurrency, such as ConcurrentHashMap. If you think that VarHandles could be used to improve those types, you should file a feature request. It's entirely possible that just nobody's bothered to do it.

  • Related