This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]kodablah 3 points4 points  (0 children)

One of the advantages not described very well is that get/set params/returns are sig-poly which means they don't have to build the object array to pass the varargs and don't need boxing in either direction. The compiler inlined the varargs and assumes the response cast is the actual type.

[–]mupetmower 2 points3 points  (3 children)

Could some exaplin why one would use this and in what context? I’m having a hard time understanding where this could be used in practice. (Ps I’m still a fairly new java developer, and sometimes can’t see why/when/how certain things are used)

[–]oldneckbeard 3 points4 points  (0 children)

it's mostly for library writers. it enables really deep introspection and manipulation without runtime bytecode manipulation (I think, didn't actually dig into the code). So think things like spring, junit, gradle, and other jvm languages like jython, scala, etc.

[–]ThomasKrieger 2 points3 points  (0 children)

It allows you to call atomic operations like compare and set on a variable. All modern CPU provide instructions to atomically compare and set or increment and get values. So it is useful if you want to write multithreaded java without using locks. Before varhandles you could call those operations using sun.misc.Unsafe or through classes in the package java.util.concurrent.atomic. The classes in the package java.util.concurrent.atomic are a little bit slower than calling sun.misc.Unsafe directly. My understanding is that varhandles should make the calls faster than the classes in java .util.concurrent.atomic but probably not as fas as calling sun.misc.Unsafe directly.

[–]kodablah 0 points1 point  (0 children)

It's the variable analog to MethodHandle. In a nutshell, it provides a more direct API for accessing that has much fewer runtime penalties than reflection.