Making Operations on Volatile Fields Atomic
Join the DZone community and get the full member experience.
Join For FreeThe expected behaviour for volatile fields is that they should behave in a multi-threaded application the same as they do in a single threaded application. They are not forbidden to behave the same way, but they are not guaranteed to behave the same way.
The solution in Java 5.0+ is to use AtomicXxxx classes however these are relatively inefficient in terms of memory (they add a header and padding), performance (they add a references and little control over their relative positions), and syntactically they are not as clear to use.
IMHO A simple solution if for volatile fields to act as they might be expected to do, the way JVM must support in AtomicFields which is not forbidden in the current JMM (Java- Memory Model) but not guaranteed.
Why make fields volatile?
Thread 2: int a = 5; Thread 1: a = 6;
Thread 2: System.out.println(a); // prints 5
Thread 2: volatile int a = 5; Thread 1: a = 6;
Thread 2: System.out.println(a); // prints 6
What are the limitations of volatile?
What can you do about it?
Thread 2: AtomicInteger a = new AtomicInteger(5);
What do I propose?
current method | suggested syntax | notes |
---|---|---|
x.getAndIncrement() | x++ or x += 1 | |
x.incrementAndGet() | ++x | |
x.getAndDecrment() | x-- or x -= 1 | |
x.decrementAndGet() | --x | |
x.addAndGet(y) | (x += y) | |
x.getAndAdd(y) | ((x += y)-y) | |
x.compareAndSet(e, y) | (x == e ? x = y, true : false) | Need to add the comma syntax used in other languages. |
These operations could be supported for all the primitive types such as boolean, byte, short, int, long, float and double. Additional assignment operators could be supported such as
current method | suggested syntax | notes |
---|---|---|
Atomic multiplication | x *= 2; | |
Atomic subtraction | x -= y; | |
Atomic division | x /= y; | |
Atomic modulus | x %= y; | |
Atomic shift | x <<= y; | |
Atomic shift | x >>= z; | |
Atomic shift | x >>>= w; | |
Atomic and | x &= ~y; | clears bits |
Atomic or | x |= z; | sets bits |
Atomic xor | x ^= w; | flips bits |
What is the risk?
JEP 193 - Enhanced Volatiles
class Usage { volatile int count; int incrementCount() { return count.volatile.incrementAndGet(); } }
- The syntax is fairly significant change. Changing the JMM might not require many changes the the Java syntax and possibly no changes to the compiler.
- It is a less general solution. It can be useful to support operations like volume += quantity; where these are double types.
- It places more burden on the developer to understand why he/she should use this instead of x++;
Conclusion
Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments