+ Start a Discussion
sfdcboysfdcboy 

how does stopping recursion on trigger works?

Everyone writes below code to stop recursion.
public Class checkRecursive{
    private static boolean run = true;   
  public static boolean runOnce()
{   
  if(run)
{
     run=false;   
  return true;  
   }
else{
        return run;    
}
    }
}
But how does it work considering if there are 100 users simutaneouly using the appilication and they updated something to fire the trigger.
if(Trigger.isBefore)
{
if(Trigger.isInsert && checkRecursive.runOnce()){
}
}

Now for the first user it will run set run to false , for rest 99 users it wont even execute as run= false as static variable are shared across sessions ie value wont reset .


I'll be really grateful if somebody could shed some light on it.
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Rohit Goel,

In order to avoid the situation of the recursive call, make sure your trigger is getting executed only one time. To do so, you can create a class with a static boolean variable with default value true.

In the trigger, before executing your code keep a check that the variable is true or not.
Please refer the below link for reference. Hope it will be helpful.

Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.

Thanks
Rahul Kumar

 
sfdcboysfdcboy
I managed to solve the query. 
Unlike Java static variables are not shared among different sessions . In Apex static variable retain value only in execution context.
ie Let's say two different users access the same visual force page and perform an action - then we have two execution contexts here and the value of this variable 'state' will be different between the two different execution contexts. This is in contrast to java where once the static variable is initialized, the value of the static variable is same to all users.