Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is atomic?

These are two atomic operations:

int value = 5;
Object obj = new Object();

But when using a primitive as a method parameter, would this be considered as an atomic operation: public void setValue(int val, Object obj){
this.value = val; // Atomic?
this.obj = obj; // Not atomic?
}

? The copy of the object reference is not atomic since it includes a read and a write, right?

Would it be correct to say that the only way to make an atomic operation on an object reference is to declare it null or assign a new object to it, like:

Object obj = null;

and

Object obj = new Object();

?

like image 392
Rox Avatar asked Apr 23 '26 03:04

Rox


1 Answers

If the parameter in the above method was a reference to an object, then the operation would not be atomic, right?

In general this is correct. A good rule of thumb is to consider there is no atomicity at all, even with primitives like:

int b,c; 
int a = ++b - c;

only primitives, but the whole assignment is potential not atomic.

If you need enshure atomic operations you have diferent posibilities:

  • synchronised blocks
  • immutable objects
  • specific libraries (java.util.concurrent.atomic)
like image 137
PeterMmm Avatar answered Apr 24 '26 19:04

PeterMmm



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!