0

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?

2
  • Unless obj.update(...) is atomic, the third method might not work.
    – Lawrence
    Jan 27, 2016 at 11:48
  • obj.update(...) is atomic. Jan 27, 2016 at 12:02

1 Answer 1

2

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.

3
  • That's a good point. So I should remove all getters and setters and include something similar to UpdateObject for reading. 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
    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
    Jan 27, 2016 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.