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?
1 Answer 1
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.
-
That's a good point. So I should remove all getters and setters and include something similar to
UpdateObject
for reading.user3998276– user39982762016年01月27日 12:03:49 +00:00Commented Jan 27, 2016 at 12:03 -
Well... it makes it safe against non-atomic reading. You can't forget to use it (unlike the locks or synchronized). But does it make the code harder to read or harder to write? How often is atomicity relevant? And if two threads change the properties simultaneously, atomicity isn't all; you still don't know who comes first and who comes second and finally succeeds.gnasher729– gnasher7292016年01月27日 16:06:34 +00:00Commented Jan 27, 2016 at 16:06
-
If you had four properties top, left, bottom, right then you probably should change them to one property "rectangle" for example.gnasher729– gnasher7292016年01月27日 16:07:23 +00:00Commented Jan 27, 2016 at 16:07
obj.update(...)
is atomic.