Mats Johansson
Mats Johansson

Reputation: 87

How do I get current thread num in a Java Request Sampler?

Developing a custom Java request sampler and trying to get the current Thread number for each thread (I assume a thread equals each Thread/Users in the thread group and is executed as a separate thread in the Java sampler?). Doing the below in the setupTest method in the sampler always gives me the same thread number (0) even when using multiple Threads in the Threadgroup?. What do I do wrong?

public void setupTest(JavaSamplerContext context){ 
cThreadNum = JMeterContextService.getContext().getThreadNum();  //cTHreadNum defined as int in the class definition
...
}

Upvotes: 0

Views: 417

Answers (1)

Dmitri T
Dmitri T

Reputation: 168082

I cannot reproduce your issue:

enter image description here

And my class is an exact replica of what you did:

package com.example;

import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThreadNum extends AbstractJavaSamplerClient {

    private static final Logger LOG = LoggerFactory.getLogger(ThreadNum.class);

    @Override
    public void setupTest(JavaSamplerContext javaSamplerContext) {
        int cThreadNum = javaSamplerContext.getJMeterContext().getThreadNum();
        LOG.info("Current thread number: " + cThreadNum);
    }

    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        return null;
    }

}

so make sure that you're using the up-to-date code, i.e. do a clean compilation and replace your class or .jar in JMeter Classpath

Also be aware that it's possible to use JSR223 Test Element and Groovy language, with enabled caching of the compiled scripts it will provide nearly the same performance.

Upvotes: 1

Related Questions