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?
obj.update(...)
is atomic.