Site icon Vinsguru

JMeter – Understanding the Scope of Variables & Sharing among Threads and Thread-Groups

In this article, We will see how we could define variables in JMeter in such a way that they can be accessed by

Scope: Local to Thread:

Creating Variables at Run Time – Multiple Threads:

By default, creating any new variables are local to a thread. It can not be accessed by other threads in the same thread group / other thread groups in the Test plan. Any change in the value does not get reflected in other threads/groups.

Lets see a simple demo.

 

ctx.getThreadNum() - returns the current thread number. It starts from 0.

Above execution result confirms that variables are local to a thread.

Creating Variables at Run Time – Multiple Iterations:

By default, a variable created for a thread retains its value throughout the test (even with multiple iterations) until it is reset.

Lets see a simple test how variables work with iterations.

Above execution result confirms that variables are local to a thread & they retain the value unless it is reset.

User Defined Variables  – Multiple Threads:

Above example explained creating variables at run time and their scope. So, what about User Defined Variables?

 

Scope: Global – All Threads in Test Plan:

Sharing Variables Using Properties:

Whenever you need to share the variable among all the threads in the Test Plan, Best way to share it using Properties.

Properties with Objects:

Unlike variables, properties can also store objects.

props.put("mylist", new ArrayList());
props.get("mylist").add(ctx.getThreadNum());
log.info(props.get("mylist").toString());

Sharing Variables Using bsh.shared Namespace:

bsh.shared is a special static space which is shared across all interpreter instances in beanshell. It can be used like properties.

bsh.shared.mylist=new ArrayList();
bsh.shared.mylist.add(ctx.getThreadNum());
log.info(bsh.shared.mylist.toString());

 

Scope: Local to Thread Group:

When you have multiple thread groups in your test plan, sometimes you might want to share the info only among all the threads within the thread group. Not with the threads in the other thread groups!

Creating some variables specific to a thread group, which can be shared by all the threads, can be done using BeanShell Init function.

beanshell.function.init=BeanShellFunction.bshrc
int i = 0;

getUpdatedValue(){
  return i++;
}
int val = ${__BeanShell(getUpdatedValue())};
log.info("Value : " + val);

 

Happy Testing & Subscribe 🙂

 

 

Share This:

Exit mobile version