Drools :: Stateful vs Stateless Knowledge Session

KieSession (Stateful Session) – is long lived and allow iterative changes over timemeans. It will continue from whatever state the session was when the previous command ended. For example, all data that was inserted into the session will still be there. Some common use cases for Stateful Sessions are: stock market monitoring and analysis for semi-automatic buying, validation of legality for market trades. Since Stateful Knowledge Session is the most commonly used session type it is just named KieSession in the KIE API. KieSession also supports the BatchExecutor interface, like StatelessKieSession, the only difference being that the FireAllRules command is not automatically called at the end for a Stateful Session. In contrast to a Stateless Session, the dispose() method must be called afterwards to ensure there are no memory leaks, as the KieBase contains references to Stateful Knowledge Sessions when they are created.

StatelessKieSession – stateless means a new session is created for each request (so no state is maintained). Stateless session, not utilising inference, forms the simplest use case. A stateless session can be called like a function passing it some data and then receiving some results back. Some common use cases for stateless sessions are, but not limited to: validation, calculation.


Difference between Stateless and Stateful Session:

Stateless SessionStateful Session
Any changes in the facts while executing rules is not made aware to the rule engine so if any rule is modified no other re-activation of rules will take place.As any changes in facts is available to the rule engine so if a rule is modified for a particular fact, this change will re-activate all the rules and fire the rules that are build on modified fact.
The engine is caused to “fire” via a call to one of the execute() methods.
1. execute(Object fact)
2. execute(Iterable facts)
3. execute(Command command)
The third version of execute() allows us to interact with the session using a command pattern (java design Command Pattern).
Provide a variety of methods to cause the engine to “fire” (i.e. execute the consequences of rules scheduled for activation).
fireAllRules(AgendaFilter filter)
fireAllRules(AgendaFilter filter, int max)
fireAllRules(int max)
fireUntilHalt(AgendaFilter filter)
dispose() method is called automatically to release the session.dispose() method should be called to release the session to avoid memory leaks.


Java Design Command Pattern








Leave a Reply