JBoss Drools Stateful vs Stateless Knowledge Session | JavaInUse






Understand Drools Stateful vs Stateless Knowledge Session



Overview

In previous chapter we implemented a drools project using KieSession to get stateful session. In this tutorial we will try to understand the difference between drools stateful and stateless session using example. Stateless session that forms the simplest use case, not utilizing inference. A stateless session can be called like a function, passing it some data and then receiving some results back. Stateful sessions are longer lived and allow iterative changes over time. Next we execute the same rule file in stateful and stateless session environment and understand the difference.

JBoss Drools - Table of Contents

JBoss Drools Hello World JBoss Drools Hello World-Stateful Knowledge Session using KieSession JBoss Drools- Understanding Drools Decision Table using Simple Example Understand Drools Stateful vs Stateless Knowledge Session Drools Tutorials- Backward Chaining simple example Drools Tutorials- Understanding attributes salience, update statement and no-loop using Simple Example Drools Tutorials- Understanding Execution Control in Drools using Simple Example Drools Tutorials- Integration with Spring MVC Drools Tutorials- Integration with Spring Boot

Video

This tutorial is explained in the below Youtube Video.

Lets Begin

Stateful Session in Drools-
Create the project as follows-
Create the model class Counter as follows-
package com.javainuse.model;

public class Counter {
	public String name;
	public int count;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Counter(int cnt, String name) {
		System.out.println("creating new using overloaded constructor");
		this.count = cnt;
		this.name = name;
	}
}
The rules.drl file will be as follows-
package rules
 
import com.javainuse.model.Counter
 
rule "Counter shower 1" 
    when $Counter  : Counter() 
 then 
    System.out.println("Counter there (1) : " + $Counter.count + " and the name is : " + $Counter.name);
 end

 rule "Counter shower 2" 
when 
    $Counter  : Counter()  
    accumulate (Counter() ; $cnt : count())
then 
    System.out.println("Counter there (2) : " + $Counter.count + " and the name is : " + $Counter.name
    +" accumaulated value is " +$cnt);
end 

rule "Counter shower 3" 
when 
    Counter()  
then 
System.out.println("Counters there (3) : ");
end
Finally we define DroolsTest class. Here load the facts and the rules in the drools working memory and firing all the rules. We make use of stateful session for firing the rules.
package com.javainuse.main;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import com.javainuse.model.Counter;

public class DroolsTest {

	public static final void main(String[] args) {
		try {
			// load up the knowledge base
			KieServices ks = KieServices.Factory.get();
			KieContainer kContainer = ks.getKieClasspathContainer();
//get stateful session
KieSession kSession = kContainer.newKieSession("ksession-rule");

			Counter counter1 = new Counter(1, "cnt1");
			Counter counter2 = new Counter(2, "cnt2");

			System.out.println("fire rules after inserting counter1");
			kSession.insert(counter1);
			//fire rules with counter1
			kSession.fireAllRules();

			System.out.println("fire rules after inserting counter2");
			kSession.insert(counter2);
			//fire rules with already existing counter1 and newly inserted counter2
			kSession.fireAllRules();

			//Dispose the session at the end.
			kSession.dispose();
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

}
On running the DroolsTest class as a java application we get the output as-
We have a stateful session here. Initially when counter1 is inserted and rules fired all three rules get fired. Later we insert counter2 and fire rules again. In this case the execution of rule "Counter shower 2" changes the value of cnt in working memory.
As this is a stateful session so this rule is again executed for counter1 also as working memory value is changed.

Stateless Session in Drools- Create the project as follows-
Create the eclipse project as follows-
Create the model class Counter as follows-
package com.javainuse.model;

public class Counter {
	public String name;
	public int count;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Counter(int cnt, String name) {
		System.out.println("creating new using overloaded constructor");
		this.count = cnt;
		this.name = name;
	}
}
The rules.drl file will be as follows-
package rules
 
import com.javainuse.model.Counter
 
rule "Counter shower 1" 
    when $Counter  : Counter() 
 then 
    System.out.println("Counter there (1) : " + $Counter.count + " and the name is : " + $Counter.name);
 end

 rule "Counter shower 2" 
when 
    $Counter  : Counter()  
    accumulate (Counter() ; $cnt : count())
then 
    System.out.println("Counter there (2) : " + $Counter.count + " and the name is : " + $Counter.name
    +" accumaulated value is " +$cnt);
end 

rule "Counter shower 3" 
when 
    Counter()  
then 
System.out.println("Counters there (3) : ");
end
Finally we define DroolsTest class. Here load the facts and the rules in the drools working memory and firing all the rules. Here we obtain stateless session and execute the rules.
package com.javainuse.main;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.StatelessKieSession;

import com.javainuse.model.Counter;

/**
 * This is a sample class to launch a rule.
 */
public class DroolsTest {

    public static final void main(String[] args) {
        try {
            // load up the knowledge base
	        KieServices ks = KieServices.Factory.get();
    	    KieContainer kContainer = ks.getKieClasspathContainer();
    	    
//get stateless session
StatelessKieSession kSession = kContainer.newStatelessKieSession();

           
        	Counter counter1 = new Counter(1,"cnt1");
            Counter counter2 = new Counter(2,"cnt2");

            //execute with counter1
            kSession.execute(counter1);

          //execute with counter2
            kSession.execute(counter2);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
On running the DroolsTest class as a java application we get the output as-
We have a stateless session here. Initially when counter1 is inserted and rules executed. Later we insert counter2 and execute rules again. In this case the execution of rule "Counter shower 2" changes the value of cnt in working memory.
As this is a stateless session each session gets disposed after getting executed.
So execution of counter1 and counter2 are independent of each other

Difference between Stateless and Stateful Session -

The major differences are-
Stateless Session Stateful Session
Any changes in the facts while executing rules is not made aware to the rule engine. Any changes in the facts while executing rules is made aware to the rule engine.
dispose() method is called automatically to release the session. dispose() method should be called to release the session to avoid memory leaks.
The engine is caused to “fire” via a call to one of the execute() methods.
The two variants are; 1) pass a single object/fact, or 2) pass an iterable object
that contains the fact(s) that will be used.
Provide a variety of methods to cause the engine to “fire” (i.e. execute the consequences of rules scheduled for activation).
fireAllRules()
fireAllRules(AgendaFilter filter)
fireAllRules(AgendaFilter filter, int max)
fireAllRules(int max)
fireUntilHalt()
fireUntilHalt(AgendaFilter filter)
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.

Download Source Code

Download it -
Drools using Stateful Session
Drools using Stateless Session
JBoss Drools Hello World
JBoss Drools Hello World-Stateful Knowledge Session using KieSession
JBoss Drools- Understanding Drools Decision Table using Simple Example
Drools Tutorials- Backward Chaining simple example
Drools Tutorials- Understanding attributes salience, update statement and no-loop using Simple Example  
Drools Tutorials- Understanding Execution Control in Drools using Simple Example
Drools Tutorials- Integration with Spring
Drools Interview Questions
Drools-Main Menu.