从一个脚本谈loadrunner的脚本初始化

 

昨天一个同事问我,如何实现下列代码中 InputStream类is对象的实例化?

 

* LoadRunner Java script. (Build: _build_number_)
*
* Script Description:
*
*/
import lrapi.lr;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.google.common.io.ByteStreams;
import com.demo.DemoFileSystem;
public class Actions
{
        File file = new File("C:/8K.file");
        InputStream is =null; 
        // 返回一个byte数组
        byte[] fileBytes = new byte[(int) file.length()];
        // 创建一个数据来保存文件数据
        DemoFileSystem dfs =new DemoFileSystem();

        public int init() throws Throwable {
            is = new FileInputStream(file);
            ByteStreams.readFully(is, fileBytes);
            is.close();        
            return 0;
        } //end of init
        
        public int action() throws Throwable {
            try {
                lr.start_transaction("dfs-w");
                String key = dfs.writeBytes(fileBytes);
                //上传
                System.out.println(key);
            } catch (Exception e) {
                e.printStackTrace();
            }
            lr.end_transaction("dfs-w", lr.AUTO);
            return 0;
        }//end of action
        
        public int end() throws Throwable {
            return 0;
        }//end of end
        
}

尝试一:我们知道,在loadrunner的java_vuser协议的脚本中,init方法在每个vuer初始化的时候都会被执行一次,换句话说N个用户就会被执行N次,所以上面的脚本中inputStream对象会被初始化N次。我随即做了如下修改

          

    File file = new File("C:/8K.file");
    static InputStream is =null;
    // 返回一个byte数组  
    byte[] fileBytes = new byte[(int) file.length()];
 public int init() throws Throwable {
        if(is==null){
            is = new FileInputStream(file);
        }
        ByteStreams.readFully(is, fileBytes);
        is.close();    
        //初始化
        return 0;
    }//end of init

理论上来说,上述代码实现了单例模式。但是这个脚本并发下无效。。。 经过和开发探讨最终换了以下的代码来处理:

尝试二:

static {
    File file = new File("C:/8K.file");
    fileBytes = new byte[(int) file.length()];
    // 创建一个数据来保存文件数据
    try {
        InputStream is = new FileInputStream(file);
        ByteStreams.readFully(is, fileBytes);
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
   
}

 

思考:

    第一种解决方法采取的是“饱汉单例模式”、非线程安全的,第二种则是使用了静态初始化块所以没有线程安全问题,如果使用“饿汉单例模式”是不是也可以实现呢?

 

posted on 2015-01-05 18:24  babyblue  阅读(990)  评论(0编辑  收藏  举报