4

I am having one thread groups in my j-meter test plan and I want to pre-initialize two map. like

java.util.HashMap myMap1 = new java.util.HashMap();
myMap1.put("foo1","bar1");
myMap1.put("foo2","bar2");

java.util.HashMap myMap2 = new java.util.HashMap();
myMap2.put("mykey",myMap1);

and I have to use it for different threads.Can anyone help me to sort out this problem?

Avyaan
  • 1,285
  • 6
  • 20
  • 47

2 Answers2

3

Depending on what test element you're using for scripting there could be 2 options:

  1. If you use Beanshell Sampler - the easiest option is using bsh.shared namespace as

    In first thread group:

    Map myMap1 = new HashMap();
    myMap1.put("foo","bar");
    bsh.shared.myMap = myMap1;
    

    In second thread group:

    Map myMap1 = bsh.shared.myMap;
    log.info(myMap1.get("foo"));
    
  2. More "generic" way is using JMeter Properties. A shorthand to current instance of JMeter Properties is available as props in any script-enabled test element (JSR223 Sampler, BSF Sampler, etc.) and it is basically an instance of java.util.Properties class hence it has put() method which accepts arbitrary Java Object as value. So

    In first thread group:

    Map myMap1 = new HashMap();
    myMap1.put("foo","bar");
    props.put("myMap", myMap1);
    

    In second thread group:

    Map myMap1 = props.get("myMap");
    log.info(myMap1.get("foo"));
    
Dmitri T
  • 159,985
  • 5
  • 83
  • 133
-1

If you need to share such stuff among multiple threads then go Singleton Object. Since single object will be shared among all the threads therefore all the threads will see the same change.

For more explanation follow the below snippet :-

import java.util.HashMap;

public class SingletonMap {
    private  HashMap myMap1 = null;
    private  HashMap myMap2 = null;
    private static volatile SingletonMap singletonMapObj = null;

    private SingletonMap(){
        myMap1 = new HashMap();
        myMap2 = new HashMap();

        myMap1.put("foo1","bar1");
        myMap1.put("foo2","bar2");

        myMap2.put("mykey",myMap1);
    }

    public static SingletonMap getSingletonMap(){
        if(singletonMapObj == null){
            new SingletonMap();
        }

        return singletonMapObj;
    }
}