Today I saw this utility class for AtomicEnum but I wonder if it is possible to have an atomic enum why it is not included in Java standard libraries? In fact I have so much doubt if it can be really atomic and if this utility class works.
The AtomicEnum class is this
Today I saw this utility class for AtomicEnum but I wonder if it is possible to have an atomic enum why it is not included in Java standard libraries?
The AtomicEnum
class that you linked to is just wrapping the AtomicReference
class which gives concurrent access for any Object
.
Really a volatile enumField
is all you need if you have multiple threads that are getting and setting it concurrently. The volatile
keyword ensures that updates made by one thread are seen by other threads.
You need the AtomicReference
if you need to do a compareAndSet(...)
type of method – atomically test if the field is a particular value and only then update it. You could use AtomicReference
something like the following:
private final AtomicReference<MyEnum> atomicColor = new AtomicReference<>();
...
atomicColor.set(ColorEnum.RED);
...
if (atomicColor.compareAndSet(ColorEnum.RED, ColorEnum.GREEN)) {
...
}
...
ColorEnum color = atomicColor.get();
How can I examine if it does the operations atomically?
AtomicReference
is part of the java.util.concurrent
classes which are well tested.
Is there a tool for seeing the compiled code and be sure that it does really all in only one machine instruction?
That shouldn't be necessary. You can take a look at the AtomicReference
source if you care to see what it is doing. Unfortunately the real magic is in the sun.misc.Unsafe
native code.
Is it possible to discover it from the code?
That shouldn't be necessary.
So if this Atomic enum works, I can have an attribute AtomicEnum and it will be possible to use it safely without volatile keyword and synchronized getters and setters?
Yes, AtomicReference
wraps a volatile V value
so you don't have to do it.
This AtomicEnum
is simply a thin wrapper around an AtomicReference
, which makes sense since a n enum
value is simply an object (reference).
So if AtomicReference
works correctly (and I think we can assume that), the AtomicEnum
will work as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With