Shared cache is always cleaned on script reload

Currently I play a bit with the shared cache and I observed a strange behavior.

the following python code should increase the counter with every script file reload

from scope import cache

value = cache.sharedCache.get("test")
if value is None:
    value = 0
print(value)
cache.sharedCache.put("test", value + 1)

after each reload it just prints 0… always.

My first guess was that it has something to do with my python binding. So I tried the same with javascript

value = cache.shared.get('test');
if( value == null ) value = 0;
console.log(value);
cache.shared.put('test', value + 1);

with the same result… It always prints 0

next guess was that it has something to do with my openhab 5.1 Installation, so I created a small test setup with a clean openhab 5.2-snapshot docker container… but with the same result.

the only scenario where I got it always working was, when python and javascript was activated at the same time. Then it was working as expected.

has anyone an idea?

Somewhere I read that the cache is cleared if you reload your file and there is no other rule use this cache.

So if you use the cache in more than one file the cache is stored. If the cache is used only in one file it gets cleared after you reload the file.

I know @rlkoshak knows more. :wink:

Greets

@Baschtlwaschtl is correct. The shared cache keeps track of which rules reference a value stored in it. When no rules are left referencing a value the cache cleans it up by removing it.

Since you only have the one rule using this value “test”, when the file is reloaded the old rule gets removed, no more rules are referencing “test” so the cache removes it. When the rule is reloaded it sees no value is stored in “test” so it initializes it with 0.

As @Baschtlwaschtl points out, if “test” is accessed by more than one rule from different files, the value will be preserved because there will be at least one rule still active referencing the value. You’d have to unload both rules at the same time for the cache cleanup to kick in and delete the value.

Note, this cleanup does more than just set the value to null. If it’s a timer, the cleanup will cancel the timer before setting the cache entry to null so you won’t end up with orphaned timers hanging around.

1 Like