1
votes

what is the difference between stateless session and stateful session in drools. I have gone through different document and found below

Stateless 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.

Stateful Session 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.

can any one explain me the above difference with example.

I was trying to execute the below rules and found same result

rule "first rules"
    when
        m : Message( status == Message.HELLO , myMessage : message )
    then
        System.out.println("first Rule");
        System.out.println( myMessage );


end

rule "second rules"
    when
        m : Message( status == Message.GOODBYE , myMessage : message )
    then
        System.out.println("second Rule");
        System.out.println( myMessage );


end

rule "third rules"
    when
       m : Message(  status == Message.GOODBYE , myMessage : message )
    then
        System.out.println( "third Rule" );
        System.out.println( myMessage );

        m.setMessage( "Hello " );
        m.setStatus( Message.HELLO );
       update(m);


end
1

1 Answers

1
votes

You can refer to drools documentation to understand difference between stateless and stateful kiesession. They are explained with examples.

Stateless KieSession -: A stateless KIE session is a session without inference. A stateless session can be called like a function in that you can use it to pass data and then receive the result back.

It doesn't support fireAllRules() from Java code. The execute method of Stateless KieSession will internally instantiate a KieSession, add all the user data and execute user commands, call fireAllRules(), and then call dispose(). So every time you call execute KieSession is re instantiated, user data are inserted again, rules are fired and dispose method is called again.

For eg -:

kStatelessSession.execute(isertObject);
kStatelessSession.execute(isertObjectAgain);

Stateful KieSession -: A stateful session allow you to make iterative changes to facts over time. So here the facts inserted to KieSession would be available till the kieSession is valid.

For eg-:

kStatefulSession.insert(object1);
kStatefulSession.insert(object2);
kStatefulSession.insert(object3);
kStatefulSession.fireAllRules();
kStatefulSession.insert(object4);
kStatefulSession.insert(object5);
kStatefulSession.fireAllRules();

Here object1, object2, object3 would be available in session even when 2nd time fireAllrules() is called. Try out the example mentioned in "stateful_kie_session" part of the documentation. You will understand the difference.