Wednesday, March 27, 2013

Sharing session ids across threads in jmeter

Problem i want to use the same JSESSIONID across the test plan which includes several Thread Groups(
Which is actually two problems
a. How do I share data between threads in JMeter?
b. How do I connect to an existing session in JMeter given the session id?
Note : A good question to ask at this stage is do I really , really want to do this? Usually a Jmeter thread maps to actions that a user can take (AJAX aside) - doing something like the above goes away from the JMeter model of things and an alternative to consider is why don't I change my test so that a user's session is only needed for a thread? (mini rant - This is a common scenario in support where there is a problem X , the user thinks that doing A will solve his problem, A needs B to be done , B needs C and C needs D and the user then asks "How do I do D?"without revealing his cards - in this case why is the test plan for a user split across multiple thread groups?) The user should really be asking how do I solve problem X because some person might say why not do Action Y which is simple) .

But because we will have a blog post to write , we will assume the answer to the above question is Yes, I really want to do this and this is the best way to solve the problem I have.

How to share data between threads in JMeter
JMeter's only out of box way to share data between threads is the properties object and the shared namespace in BeanShell[2] both of which have limitations. The properties object needs you to come up with some scheme to share data and also needs you to write your own code for e.g. if you consume data much faster than you can generate it.

One technique is that if ALL the data that is to be shared is to be obtained before the next threads need it then one option is to use the CSV Data Set config - The first set of threads write to the file and the next set of threads read from this file - but essentially any shared memory(e.g. a file, a database etc) will do. However if you need to read and write this data at the same time then another way is to use the standard Java data structures which are thread safe.

In this post we will look at two ways
a. The CSV data set config
b. Using a java object
Note that there is a plugin available which will do b. from Jmeter plugins InterThreadCommunication [1] . If you aren't a programmer then the plugin is probably best for you - though I will say that good testers these days need to have programming and scripting skills.

However we will just write our own for fun. You also might need to do this to implement a complicated scheme.

Before we begin we will need an application to allow us to test whatever we write. So I have deployed a web application which has 2 URLs
a. set.jsp which sets an attribute into the session with the name uuid and the value a random generated value and also returns it as part of its output. Since this is the first page we access it will also create a session and set a cookie.

b. get.jsp which reads the value of the attribute uuid and returns it as its output. If you have the same session and previously accessed set.jsp then you should see the same value as step a.
If you dont have a session(or didnt access set.jsp) then you will see the value as "null"

So let us first write a simple test to verify that all is well. Here is a screen of the test.

We simply access set.jsp. Extract out its response . Then we access get.jsp and assert that the value we extracted out matches whatever is being returned by get.jsp. If the same session is being used for both the requests then the assertion will pass , otherwise it will fail.

Remember that Java web applications allow sessions to be maintained in two ways - either the Session ID is passed as part of the URL or as a cookie (usually named JSESSIONID) or both.
For this example we will assume we are using cookies.

Lets cause the test to fail - A simple way of doing this is by disabling the HTTP Cookie Manager. If we disable this JMeter wont accept cookies and hence wont be able to maintain sessions and every request will be a new session.

So we disable the HTTP Cookie manager and run the test. It fails as we expected it. Lets verify that it's because of the session
a. Note the first request gets a Set-Cookie back from the server - the server is trying to get the client to store the SessionID so that the next request can send the SessionID back

b. Note that the next request does not send a cookie header from JMeter

c. Note that the server responds to this request with another set-cookie (because it will try to create a new session as it didnt get any existing session cookie

Now lets enable the HTTP Cookie Manager. It works!. Lets verify the cookie was passed

Now that we have some degree of confidence that our assertions work (i.e. failures are flagged as failures and successes as successes) lets rerun the test with multiple threads and multiple iterations. All work. We can also see that different set requests get different cookies. This is because a cookie manager is scoped to a single thread (so each thread gets its own cookie and session) and because we have checked  "Clear cookies at each iteration" on the cookie manager.

Sharing Data using Java Objects in realtime
Lets first create a class that will allow data to be shared. For this purpose we use a  LinkedBlockingQueue  [4]. The javadoc for the interface BlockingQueue.
"Note that a BlockingQueue can safely be used with multiple producers and multiple consumers."
Which is a fancy way of saying something can be accessed by multiple threads without the programmer needing a degree in Computer Science. Since we will be reading and writing from different threads in different thread groups , the fact that this data structure natively supports thread safety frees us up from having to implement it - no synchronized keywords are needed in our code
However we do need to store this queue object somewhere , so we simply create a wrapper class that holds on this Queue statically and provide getters and setters. Because we dont know the rate at which we will read/write we simply put a timeout on the get.

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Queue {
    private static LinkedBlockingQueue<Object> q = new LinkedBlockingQueue<Object>();
    public static void put(Object o) throws Exception{
    public static Object get(long timeout) throws Exception{
        return q.poll(timeout, TimeUnit.MILLISECONDS);
    public static void clear() throws Exception{
    public static void main(String [] args) throws Exception{

We run a simple single threaded test on this class to see that everything is fine (it is), we compile this into a jar, place the jar in JMeter's lib directory and our class is ready to be used.
 The test structure is shown in the screen below

a. The setup thread group clears any data that might already be there in the queue. Because we are holding onto the Queue statically and the JMeter GUI is a single JVM , we need to clear out any data that might be there from a previous run. This is the code in the Beanshell sampler.;

b. We create a threadgroup and use a request to create the sessions , extract out the data that we need - the sessionid and the value returned by the page so that we can assert that we are connecting to the same session. We then call the class we have just created to put these values into the queue (as an array with two values) and finally we introduce a random delay values
The regular expression to extract the cookie is in the screenshot above

And here is the BeanShell code to add the cookie and the extracted value to the Queue

String[] data = new String[2];
data[0] = vars.get("jsessionid");
data[1] = vars.get("uuid");;

c. Next we create a threadgroup that is going to use the session ids set from the previous threadgroup using a BeanShell preprocessor. The preprocessor also has the code to add the session id cookie so that requests will connect to the existing session. As before we assumed that the Server manages session in the form of cookies. But we could also have it as part of the URL once we are able to successfully read the SessionID.
We also configure the thread groups to have different number of threads so that there will be some variation in the rate of requests (note that if you have more Sessions created in the "set" threadgroup than you can process in the "get" threadgroup you will eventually run out of memory unless you make the queue bounded in size. If you have more in the "get" threadgroup then they will keep waiting (hence we have a timeout when we ask for a session id)

import org.apache.jmeter.protocol.http.control .CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;
String[] data = (String[]);
if(data != null) {
    Cookie cookie = new Cookie("JSESSIONID",vars.get("jsessionid"),"localhost","/", false,-1);
    CookieManager manager = sampler.getCookieManager();

The code above simply asks the queue for a value, and will wait upto 60 seconds for it (This only applies if we are consuming the data much faster than we can produce it). Then if we did get a valid value we use the JMeter API's[3] to access the Cookie Manager and add a cookie to it. Note that we do need a Cookie Manager for this to work.  Some values have been hardcoded for simplicity (like the domain name)

We run the test and its all successful! Remember we do have assertions so a success is indeed a success. We can also verify using the view results tree listener and we can also check the cookie is being sent in the GET request.

Cons : Note that anything that needs data to be shared between threads , that has wait and synchronization( irrespective of whether you do it or whether the JVM does) adds an overhead to the test - so the amount of load you can generate from a single JMeter instance will reduce. Also if you need more sophisticated schemes to share data (we used a simple FIFO model) then your code is more complicated , more prone to errors and likely to add more overhead.

Sharing data using files
Using a file is usually not a good candidate for sessionids because sessionids are short lived and may timeout. You also need to have everything available in the file before you can start reading the file. They are more suited to usecases like testing for Remember me or keep me signed in type of cookies. However the flexibility a CSV data set config provides may make it worth your time.
Here is the structure of the test.

The setUp thread group sends a set of requests to create the session and get the values as before.  To write all these values to a file we use a simple data writer and configure JMeter (by modifying to write the two variables we are interested in only. Note that this is probably not a good way to do it - in addition JMeter appends the data to an existing file so either you need to delete the file before you run this or use a property that varies dynamically so that a new file is created.

Remember that the setUp thread group will always execute before any other threadgroup , so this file will be created and have all the data before the next thread group runs.  The Simple data writer unchecks all the checkboxes and we edit to have the following line


The next threadgroup simply reads the file and attaches the session id to the cookie manager.

We can have as many threads as we want (we ensure that clear cookies at every iteration is checked so that every time we request something we use the cookie that is set by the beanshell preprocessor and not the one the cookie manager had previously saved). The Beanshell code to add the cookie is the same as before

import org.apache.jmeter.protocol.http.control .CookieManager;
import org.apache.jmeter.protocol.http.control.Cookie;

Cookie cookie = new Cookie("JSESSIONID",vars.get("jsessionid"),"localhost","/", false,-1);
CookieManager manager = sampler.getCookieManager();
we run the test - all successful. The file generated has the values


The cookies get added to the request

We can change the CSV data set config to keep reading the same file instead of terminating at the end - that works as well. You can also check that if you disable the setup threadgroup and rerun the test , it still works (because the sessions are still active - assuming they havent timed out) - so if the data you are saving in this file is still valid it can be used anytime and anywhere. You can also bounce the server in which the JSP web application was deployed. This causes all the sessions to get invalidated and hence the file to have invalid data. Now if you run the test , all the samples will fail because all the sessions are invalid - so even though we added the session id , the server has no data for this session.

Cons : As mentioned above , this isn't realtime sharing , it relies on you already having the data to be used , and the data being valid.

Files used in this post available at!886

[1] InterThread Communication-
[2] BeanShell Shared namespace -
[3] Cookie Manager -
[4] LinkedBlockingQueue -


Samant said...

useful info Deepak .. Thanks

Anonymous said...

I have created simple Jmeter code which can perform the following:

> I have a JSON Response message which returns an array of customer ID. Regx extractor helped me extract each individual element from the array.

> I can now use these extracted individual element stored in ergX variable to be appended to some.url/links_1 to perform another http request, which presently can be run sequentially within the same thread group.

> Here is what I want to do: to run a concurrent HTTP request (with all the individual JSON array element) in a loop, with a given delay of 1sec

- some.url/regXval_1 - 1st in a loop of 10 times
- some.url/regXval_2 - run concurrently with a delay of 1sec in a loop of 10 times

I am a beginner with Jmeter. Can you please help me with this bit of code? Thank you

Deepak Shetty said...

Thats quite complicated and not something that can be explained in a comment
Ive discussed something similar here

Anonymous said...

Can you please tell me how to overwrite the file content used in the Simple Data Writer in Jmeter. Presently everytime I run the thread, new results are being appended to the end of the old results/rows.
Thank you

Deepak Shetty said...

The only around that is to generate a different file name each time by making part of the filename variable like using a timestamp.

snippetjournal said...

i found there is very few tutorial like this. and ur sir save my day :D

Anonymous said...

How to use Beanshell guide - has this highlighter as well, perhaps will be easier to use

Marietta said...

Hi there,

I am tryig to follow your instructions here, which seem really helpful.
But I have problem on downloading the shared files you have uploaded on skydrive.
Also, could you please attach the .jar created by the wrapped class on which you define the Queue, as I have not jmeter built locally? Will it work if I use yours?

Thank you in advance,

Deepak Shetty said...

@Marietta!886 should work - is it not working? If not please mention your email address and I will email it to you.

For the jar file you dont need to build jmeter - you only need to compile the java file and package it into a jar and copy it into jmeter/lib (in this case you dont even need to add anything in your classpath since it only uses java libraries)
As such I will only be able to do this tomorrow - so give it a try and see otherwise i will upload it tomorrow(PST)

Deepak Shetty said...

@Marietta both the java file and the jar file are uploaded to!886

if the link doesnt work , please provide an email address that I can mail the files to.

Anonymous said...

Hi Deepak,

That a useful piece of information that you have shared here..
I am actually following step-by-step instructions, but when the request is getting executed, its going without cookies, surprisingly there are no errors in jmeter.log, any help is very much appreciated

Thanks a ton,

Deepak Shetty said...

what approach are you using?
Also is your application actually setting cookies? You usually have to use a Debug Sampler + View Results Tree Listener to debug what is happening at what time -
since you have not given any information I have no idea what you are doing

Anonymous said...

Hi Deepak,

I am trying out the queue approach, I guess my application is setting cookies, because I see the below in the "Sampler result" tab when the request is being fired
Set-Cookie: JSESSIONID=96C786381A67D435CF9A38C0F28693F4.node1; Path=/billpay.

I was under the impression that the Beanshell code will override and set the desired cookie.


Deepak Shetty said...

Im not sure what you are doing - but in my sample , I add the cookie to the very first request(in the GET thread group) itself so there is no question of "overriding" - so if any cookies get set in the first request , those are being added by the beanshell code.
If you are making some request and then you want to remove/update that cookie to some other value (why?) Thats also bossible via beanshell - look at the linked apis which tell you how to retrieve cookies/ delete or update them

Testing Sorttricks said...

Well, I think your blog is pretty good and have lots of useful information. Keep it up!testingsortrickseter

b lakshmi said...

Your articles are helping a lot. I am testing REST apis using Jmeter 3.1. There are few APIs which gets cookiedata(_token value) under cookieData and access_token/token value in the url path of http request (these dynamic token values are not captured in response, dynamically generated in http request itself). Please suggest me how to correlate which is in http request not in response. I am able to correlate if it is in response.
Please suggest, it would be really helpful if i am able to solve this issue as my many aPIs are dependent on this.

Deepak Shetty said...

@b lakshmi
>Please suggest me how to correlate which is in http request not in response. I am able to correlate if it is in response.
This doesnt make sense. The request is being made by the client. Any access token/cookie etc is always provided by the server (in some previous request). You need to identify that first. Once you get that , extract the data using regex post processor into a variable say variableName and you can send it in the next request using${variableName} in any place including URL