3

I read that primitive datatypes like boolean, byte, short, char, int and float are atomic. 64-bit datatypes like long and double are not.

But what does this mean? When I have 2 Threads that increment and decrement on a int variable than sometimes i still got race conditions.

for example the bytecode of adding an amount to a variable.

getfield #2 <Field int amount>
iload_1
iadd
putfield #2 <Field int amount>

Is atomic in this case every single operation (getfield, iadd...) and not the full addition?

KyleReemoN-
  • 504
  • 2
  • 8
  • 16
  • Atomic means that an operation that changes the value happens "at once" like a transaction. That doesn't mean that you won't have race conditions, it just means that you won't have race conditions because of atomicy. – Nir Alfasi Jul 05 '14 at 07:58
  • Yes i read the Are java primitive ints atomic by design or by accident? but I was not sure thats why i asked explicit if "getfield", "iload_1" is atomic – KyleReemoN- Jul 05 '14 at 08:06

1 Answers1

9

When I have 2 Threads that increment and decrement on a int variable than sometimes i still got race conditions.

Yes, you will - because even though the "get" and "set" operations on the int variable are each atomic, that doesn't mean the "increment" operation is atomic.

Is atomic in this case every single operation (getfield, iadd...) and not the full addition?

Yes, exactly. It's not actually the primitive types are atomic - it's read and write operations that are atomic. That's a big difference.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194