Subscribing to concurrent property updates

Photo by Tomas Sobek on Unsplash
  • create two Props and bind them to a registry
  • pass the two Props to a “Pair” implementation
  • for each of those Props, subscribe to any updates
  • the subscriber would retrieve both values and send an event containing both props
- set value A
- notify subscribers of value A
- set value B
- notify subscribers of value B

- notifies subscribers of value B
- notifies subscribers of value A

- the Prop's value is set to B
- but the subscribers were last sent A
  • Write tests to reproduce your scenario and expected results, then run them repeatedly (think Junit + repeat until failure, tens of thousands of times)
  • Sometimes, you need extra info to debug problems; you’d be tempted to use System.out.print(), but that can be misleading; it adds a few millis of lag which can totally derail your repro when the scenario you're trying to debug executes in nanoseconds.
  • System.out.print() lies: the output stream is buffered and can be printed in the wrong order; calling System.out.flush() helps, but is not perfect and still suffers from the orders of magnitude problem explained above
  • Two independent atomic operations do not make for one atomic operation; this is counterintuitive at first but makes total sense the more you think of it; two threads executing the same two operations could order them in 4 different ways; find a way to update both values in a single atomic operation
  • Syncing multiple props means the updates need to be ordered; I found one solution: queue the update operations and pass them to AtomicReference.updateAndGet() as UnaryOperator<Pair<T, U>. This method uses weakCompareAndSetVolatile memory effects, specified in the JLS as:


  • don’t assume ordering
  • test your code until breaking point
  • avoid implementing concurrency primitives from scratch unless there’s a real need



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mihai Bojin

Mihai Bojin

Software Engineer at heart, Manager by day, Indie Hacker at night. Writing about DevOps, Software engineering, and Cloud computing. Opinions my own.