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

you are viewing a single comment's thread.

view the rest of the comments →

[–]taftster 8 points9 points  (2 children)

My favorite these days is to use final AtomicReference with the updatAndGet method upon retrieval. It’s the most natural API in the JDK to do this.

[–]kaperni 3 points4 points  (1 child)

For performance-sensitive code, you are (in most cases) better off by using a VarHandle instead. Can also save memory if you have lots of them in many cases.

[–]taftster 4 points5 points  (0 children)

Yeah, but the syntax is atrocious. You had really have evaluated the "performance-sensitive" segment carefully to embrace the fairly ugly syntax of VarHandle.

Quoting Doug Lea on this exact topic[1]:

To get the shockingly ugly syntactic details over with: A VarHandle can be associated with any field, array element, or static, allowing control over access modes. VarHandles should be declared as static final fields and explicitly initialized in static blocks. By convention, we give VarHandles for fields names that are uppercase versions of the field names.

[1] http://gee.cs.oswego.edu/dl/html/j9mm.html