Problem with shared variable

Hi
I have a problem that is driving me crazy. I have a rule that changes the value of a variable and then calls another rule:

//Items:
Switch theVariable
Switch Rule1Trigger
String Rule2Trigger

//Rules:
rule "Rule 1"
when
    Item Rule1Trigger received update
then		
	if (Rule1Trigger.state==ON)
	{
		logInfo("Casa","theVariable in Rule 1 is "+theVariable.state)
		theVariable.postUpdate(ON)
		logInfo("Casa","theVariable in Rule 1 is "+theVariable.state)
		Rule2Trigger.sendCommand("something")
	}
end

rule "Rule 2"
when
    Item Rule2Trigger received update
then		
    logInfo("Casa","theVariable in Rule 2 is "+theVariable.state)
    theVariable.postUpdate(OFF)
    logInfo("Casa","theVariable in Rule 2 is "+theVariable.state)
end

I think I should always get:
theVariable in Rule 1 is OFF
theVariable in Rule 1 is ON
theVariable in Rule 2 is ON
theVariable in Rule 2 is OFF

But I am getting:
theVariable in Rule 1 is OFF
theVariable in Rule 1 is ON
theVariable in Rule 2 is ON
theVariable in Rule 2 is ON
Or:
theVariable in Rule 1 is OFF
theVariable in Rule 1 is OFF
theVariable in Rule 2 is ON
theVariable in Rule 2 is OFF
Or:
theVariable in Rule 1 is OFF
theVariable in Rule 1 is ON
theVariable in Rule 2 is OFF
theVariable in Rule 2 is OFF

What am I doing wrong? How can I ensure the serialization of events?
I’m still on OH 1.8.3, Oracle Java 1.8.0_151
Thanks.

You can’t really. Processing the commands is happening in a separate set of threads without locking so there is no way to guarantee order of processing.

The vast majority of time this didn’t matter but you have one of the few cases where it does.

I think the only thing you can do is add a Thread::sleep to Rule 1 to give the postUpdate time to be recovered by the event but and processed before triggering rule 2. A sheep of 100msec should be more than enough.

I do follow the explanation from @rlkoshak, however the explanation that it does take time for the postupdate to change the variable doesn’t fit the last example. Did you really see such a case? I can’t see a reason for the change of state after rule1 and before rule2.

1 Like

Yes. But I could solve it with a Thread::sleep(), thank you both.
Regards.