Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

primitive datatypes are atomic in java [duplicate]

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?

like image 730
KyleReemoN- Avatar asked May 10 '26 20:05

KyleReemoN-


1 Answers

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.

like image 178
Jon Skeet Avatar answered May 12 '26 11:05

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!