Search code examples
droolsrule-engine

What is the difference between creating a KieSession from a KieBase and a KieContainer?


I am trying to evaluate the best option for creating KieSession.

Option 1

kiebase.newKieSession();

Option 2

container = kieHelper.getKieContainer();
container.newKieSession()

I am unable to find the difference between the 2. Any inputs?


Solution

  • They're fundamentally different, as is explained in the JavaDoc.

    The method kieContainer.newKieSession() returns the default KieSession for this container. If the container has no defined default session, it will throw a RuntimeException.

    The method kieBase.newKieSession() will create a new KieSession for this KieBase following the default configuration.

    Since a KieContainer contains all of the KieBases for a KieModule, it is possible that both methods will resolve to similar KieSessions. Of course you would need to have a KieContainer that only contained a single KieBase, and the container's default session would have to be initialized with the single KieBase's default configured session.

    Consider this configuration (fields irrelevant to the question are omitted so it's not a valid kmodule.xml, obviously):

    <kmodule>
      <kbase name="foo">
        <ksession name="fooSession" type="stateless" default="true">
      </kbase>
      <kbase name="bar">
        <ksession name="barSession" type="stateless">
      </kbase>
    </kmodule>
    

    Here, if we call kieContainer.newKieSession(), we'll get back the kieSession named 'fooSession' because it is configured as the default. Similarly if we call kieBase.newKieSession() and kieBase is the one named 'foo', we'll also get back a kieSession like 'fooSession'. But if kieBase is the one named 'bar', then the session will be like 'barSession' instead.

    When it comes to figuring out how the guts of Drools work, it sometimes helps to go look at the source code in addition to the documentation. It's a bit complex to start out, but if you start at the APIs (interfaces) and then work backwards to the implementations, things start to make sense.