deliveredtechnologies / rulebook

100% Java, Lambda Enabled, Lightweight Rules Engine with a Simple and Intuitive DSL
http://www.deliveredtechnologies.com
Apache License 2.0
716 stars 124 forks source link

SpringAwareRuleBookRunner is not Thread-safe #169

Open Panthro opened 5 years ago

Panthro commented 5 years ago

In a multi thread environment (which usually is the case when creating apps with spring) the SpringAwareRuleBookRunner can create all sorts of problems.

In #53 RuleBookFactoryBean was recommended and now is deprecated (without docs on how to replace it)

I'm currently using the SpringAwareRuleBookRunner, but I have to create a new thread for each rule book execution or input and outputs are shared.

Clayton7510 commented 5 years ago

SpringAwareRuleBookRunner is a context aware extension of RuleBookRunner, which is thread safe. If I'm understanding your situation correctly, it sounds like you are creating a SpringAwareRuleBookRunner and running it multiple times in the same thread where it is updating the facts supplied and overwriting the result? If that's the case, then that is expected behavior. If instead, you would rather have each run in the same thread maintain its own state, then you can make the SpringAwareRuleBookRunner prototype scope.

Different threads can have different state for a single instance of a RuleBookRunner (or SpringAwareRuleBookRunner). But the same thread will have the same state since RuleBookRunners track execution on a per-thread basis (that's how it maintains thread safety).

In terms of replacing RuleBookFactoryBean, something like this would take its place and allow Spring to inject into its POJO rules.

  @Bean
  public SpringAwareRuleBookRunner springAwareRuleBookRunner() {
    return new SpringAwareRuleBookRunner("com.deliveredtechnologies.example.spring.rules");
  }

I'll be sure to have the deprecation description updated in RuleBookFactoryBean.