0

I'm doing some experiments with openHAB2 to control a simple relay that is linked to my garage lights.

I've created a rule for this Switch item, so the relay can switch back to the ON state after one second from the user click on the UI button.

To prevent user from multiple clicking in a short time (e.g. user clicks again after a 1st click and before the end of thread sleep), I've put a ReentrantLock and it seems to work.

When a second clicks arrives, I see an exception thrown at runtime from openHAB:

[ERROR] [ntime.internal.engine.RuleEngineImpl] - Rule 'Garage lights': 
org.eclipse.xtext.xbase.interpreter.impl.EvaluationException: java.lang.IllegalMonitorStateException

Why is it not caught from my catch block? How can I catch it?

Here is my code:

import java.util.concurrent.locks.ReentrantLock

val ReentrantLock lockLights  = new ReentrantLock()

rule "Garage lights"
        when
                Item GarageLightsSwitch received command OFF
        then
                try {
                        if(lockLights.tryLock()) {
                                Thread::sleep(1000)
                                GarageLightsSwitch.sendCommand(ON)
                        }
                }
                catch (Exception e) {
                        logInfo("Generic exception")
                }
                finally {
                        lockLights.unlock()
                }
end

The item is configured this way:

Switch GarageLightsSwitch "Garage lights" <switch> {gpio="pin:6 initialValue:high" }

My sitemap is:

sitemap default label="My sitemap" {
    Switch item=GarageLightsSwitch mappings=[OFF="CLICK ME"]
}

Thanks in advance

Roberto Milani
  • 127
  • 2
  • 7

1 Answers1

1

Why is it not caught from my catch block?

Because it is being thrown from the finally block, which happens no matter what, including if tryLock() fails. If you then call unlock() on a lock you do not hold, you get an IllegalMonitorStateException.

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantLock.html#unlock--

You could use isHeldByCurrentThread() to check if this thread actually holds the lock before trying to release it, or you could ditch finally and unlock in theif block.

goldilocks
  • 60,325
  • 17
  • 117
  • 234