Jmeter : How to initialize map once and share it for all threads in a thread group

故事扮演 提交于 2021-01-27 08:25:21

问题


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?


回答1:


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"));
    



回答2:


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;
    }
}


来源:https://stackoverflow.com/questions/28667316/jmeter-how-to-initialize-map-once-and-share-it-for-all-threads-in-a-thread-gro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!