Reasons for choosing Java agents

Rule agents are the default choice of agent, but there might be good reasons for you to choose a different type of agent.

In most cases, a rule agent is likely to be your first choice of agent. In a rule agent, you can express what you want to do more compactly than by using a Java™ agent. A major difference between rule agents and Java agents is that Java agents by default are stateless. Rule agents store the state of processed events and values of related entities in the working memory, and this data is available in a stateful way to rule conditions. To maintain state in a Java agent, you must add attributes to the bound entity.

The following examples give some valid reasons to use a Java agent rather than a rule agent:

The following general guideline can also be used to make your choice of agent:

Use else if clauses in Java agents to test multiple criteria

In a rule agent, it is not easy to perform a stop processing or suspend evaluation action when there are multiple criteria to test. To achieve this goal in a rule agent, you might need to send multiple specials when multiple criteria are met. In a Java agent, you can write Java code with else if clauses to perform this type of action.

The following code shows how to emit an event if two independent conditions on an entity are met:

public void processEvent(Event e) {
   WidgetSale ws = (WidgetSale) e;
   Widget widget = getBoundEntity();

   boolean emitSpecial = false;
   if (widget.getColor() == RED) {
      emitSpecial = true;
   }
   else if (widget.getWeight() >= 10) {
      emitSpecial = true;
   }

   if (emitSpecial) {
      emit(new Special());
   }
}