I was specifically asking how "as they happen" atomic state is. My example code snippet shows the race condition I'm worried about, already assuming that I'm using atomic state. Am I guaranteed that as soon as the set-state command finishes executing that the new state has already been written, or does setting atomic state merely enqueue the DB write for "almost immediate" write, as implied by the SmartThings documentation?
Whatever the answer, I've decided to ditch state altogether for what should really be modeled as a thread-safe, in-memory state machine, and only using state/atomic state for best-effort persistence so I can reconstruct in-memory state on Hubitat reboot.
At the time I wrote this I didnât know synchronized worked in HE. If memory serves me, it did not in ST which was a consequence of it being cloud based (two executions maybe executing on different servers) So I think I just assumed the same in HE since I could find no examples using it and no reference to it. So I did like many and assumed the ST docs were valid. Search https://docs.smartthings.com/en/latest/code-review-guidelines.html for synchronized. The reasons to not use it in ST do not apply to HR
Correct. I generally use a static @Field since that will persist across all those instances. [quote="peterwoggle, post:19, topic:21304"]
Using atomic state, is this guaranteed
// to execute at most once?
[/quote]
That I donât know for sure. I believe so, but one of the platform developers would need to chime in, I think. I believe a definitive answer relies on internal knowledge of the architecture that isnât public.
I'd say according to my testing (mentioned here) this is not guaranteed, and is indeed not much different than using regular state.
I haven't tested the @Field trick, but regular synchronized is not working. I'd say there is no thread safe way to update state in Hubitat App or Driver (UPDATE: I was wrong - static field does solve the problem).
Given that there's no way to avoid multiple threads in any real app, I'd also go further and say that simply there's no way to update state in Hubitat without race conditions (UPDATE: I was wrong). I'll try to test @Field trick soon, and I really hope it works.
Synchronized does works. However Iâve youâre not locking on a static field then youâre not locking on a shared object thus youâre not actually synchronized.