Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have an AtomicEnum in Java?

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

  1. How can I examine if it does the operations atomically?
  2. Is there a tool for seeing the compiled code and be sure that it does really all in only one machine instruction?
  3. Is it possible to discover it from the code?
  4. 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?
like image 951
Johnny Avatar asked Dec 19 '13 15:12

Johnny


2 Answers

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.

like image 94
Gray Avatar answered Sep 18 '22 22:09

Gray


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.

like image 40
Joachim Sauer Avatar answered Sep 18 '22 22:09

Joachim Sauer