Java – Concurrent and atomic updates to multiple properties/variable of an object

concurrencyjavasetters

I have a class with multiple setters and want to make atomic updates to multiple properties/variables. As far as I can see there are three methods that could work:

Call all setters in synchronized block.

synchronized {
  obj.setA(a);
  obj.setB(b);
  // ...
}

Use explicit locks.

obj.lock();
obj.setA(a);
obj.setB(b);
// ...
obj.unlock();

Use an update object.

update = new UpdateObject();
update.setA(a);
update.setB(b);
// ...
obj.update(update);

Update objects are often used by the Windows API to make atomic changes to an object without explicit locking in a single system call.

Is there any method that I missed?

Concurrency control is a cross-cutting concern. What are the architectural implication of each method? What is the most idiomatic method in Java?

Best Answer

What all these methods have in common is that the update to multiple properties is only atomic if everybody updating the properties uses the same method, but also everybody reading the properties and wanting them updated atomically reads the properties using one of these locking methods.

Your chances improve mightily if instead of having multiple properties, you have one object representing all the properties, and only have a getter / setter for that one object.

Related Topic