2

I want atomic reads and atomic writes to Integer (not int) and others as follows:

volatile Double a; // not double
volatile Long b; // not long
Integer c; // not int
Boolean d; // not boolean

If not, how would I make them atomic?

Edit: As a clarification, I do not need an atomic operation that combines read and write. I just need the read to be atomic and the write to be atomic, separately.

Edit2: @Peter Lawrey, @PeterLawrey, This is ironic: Double a; a = 0.5d; Here the write is atomic because a is a reference. While in this double a; a = 0.5d; the write is not be guaranteed to be atomic. And yet the Double wraps a double. Of course I would not expect the same to apply to the wrapped contents of arbitrary objects that have references read and written atomicly.

Edit3: Additional note, I originally wanted to get atomic reads and writes thinking that atomicity ensures consistency across threads. I found that it doesn't and that you still need volatility.

H2ONaCl
  • 10,644
  • 14
  • 70
  • 114

2 Answers2

5

All reads or writes to references are atomic.

I assume you mean you want to do a read and a write atomicly. In that case I would use AtomicReference, AtomicLong, AtomicInteger or AtomicBoolean as approriate . If performance is important to you I would use int long or double instead of wrappers.

For consistency between threads you need volatile. For atomic operations like increment and swap, you can use AtomicReference, AtomicReferenceFieldUpdater, AtomicLong, AtomicInteger, AtomicBoolean, AtomicIntegerArray, AtomicIntegerFieldUpdater and AtomicLongArray AtomicLongFieldUpdater classes. To perform such atomic operations on a double, you can build your own updater with Unsafe, but use at your own risk. ;)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Unless I have you mistaken shouldn't you use?

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/AtomicInteger.html

Instead?