Drools: using globals for information-share

view over Porto Alegre by Christoph Burmeister (own photo)

view over Porto Alegre by Christoph Burmeister (own photo)

After my last post about stateful sessions with drools and a non-enterprise topic with mixing alcohol 🙂 I just tried to figure out how to share information between rules-actions. For example to modify values in a map or whatever.

To use a global CocktailCount-object between the rules an the test, we first have to create such a class:

package org.jtaddeus.cocktailapp.cocktails;

public class CocktailCount {
	private int count;
	public CocktailCount(int count){
		this.count = count;

	public int getCount() {
		return count;

	public void setCount(int count) {
		this.count = count;

afterwards the existing unit-test has to be modified:

public void testTequilaSunrise(){
	StatefulKnowledgeSession ksession = createStatefulSession();
	CocktailCount cocktailCount = new CocktailCount(0);
	ksession.setGlobal( "globalCocktailCount", cocktailCount);			
	int n = 5;
	ksession.insert(new Grenadine(2*n)); // 2 for 1
	ksession.insert(new LemonJuice(1*n)); // 1 for 1
	ksession.insert(new OrangeJuice(12*n)); // 12 for 1
	ksession.insert(new Tequila(5*n)); // 5 for 1
	System.out.println("---disposed ksession");

        QueryResults queryResults = ksession.getQueryResults("count TequilaSunrise");
        assertEquals(n, queryResults.size()); // there must be n facts of type TequilaSunrise in WorkingMemory

so now we can add a global to the rules-drl:

global org.jtaddeus.cocktailapp.cocktails.CocktailCount globalCocktailCount;

and have to modify the rule-consequence:


With these changes, the counter-object can be used between the rule-actions and it is reflected back to the firing class (int this case the Unit-Test). There are might be better ways…