0

During OptaPlanner solving phrase, I wish to update a global variable. The changes of global variable will modify my next rules validation.

Result.java

package com.domain; 

public static boolean status;
...
...

Sample.drl

import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScoreHolder;       
import com.domain.Result;
global HardSoftScoreHolder scoreHolder; 

rule "Sample Rule"
when
 $PlanningEntity:PlanningEntity()
then
 somelogic($PlanningEntity);
 if(Result.status){
    scoreHolder.addHardConstraintMatch(kcontext, -500);
 }
end

function void somelogic(PlanningEntity planningEntity){
    if(condition 1...){
         Result.status = true;
    }else if(condition 2...){
         Result.status = false;
    }else{
         //Do Nothing
    }
}

My Question:

How can I declare the static global variable per solving session. (To avoid multiple users doing the OptaPlanner solver at the same timing.)

Geoffrey De Smet
  • 26,223
  • 11
  • 73
  • 120

1 Answers1

0

Currently you can't reliably use a global variable because OptaPlanner might spawn multiple drools sessions (needed for future features such as multi-threaded solving, population based heuristics, ...).

The workaround is simple: simply add a singleton problem fact and use that. See the *Parametrization classes in the examples.

Geoffrey De Smet
  • 26,223
  • 11
  • 73
  • 120
  • But wouldn't these Drools sessions all be part of one user's session (i.e., execution of a Java application)? Hence, there wouldn't be the kind of cross-fire OP seems to be afraid of. - BTW, the Drools reference manual doesn't even state that globals are shared between sessions run from within the same Java program (but somehow I remember this from somewhere). – laune Apr 06 '15 at 14:01
  • Each drools session used inside optaplanner would needs to have it's own global instances (unless its a thread-safe logger (or something else that it's acts only as a sink, never as a source). Creating those instances would need to happen through a callback, as optaplanner might spawn any number of drools sessions it desires (although currently it only spawns 1 in normal execution) – Geoffrey De Smet Apr 06 '15 at 20:14
  • Will it be possible to use shadow variables or adding the variables to working memory in opta-planner (Just like score holder)? I need a dynamic problem fact that can vary and apply on next rule. Example: 1st Step update Fact as "A". 2nd Step use Fact "A" in the Rule and update Fact as "B". 3rd Step use "B" in the Rule and update Fact... – Jeffrey Lai Guo Zin Apr 07 '15 at 04:53