</>

Technology

TestNG

Difficulty

Advanced

Interview Question

What is threadPoolSize in TestNG @Test and how does it work with invocationCount?

Answer

threadPoolSize + invocationCount in TestNG

These two attributes work together to run a single @Test method multiple times across multiple parallel threads.

Basic Concept

Java
@Test(invocationCount = 10, threadPoolSize = 3)
public void loadTest() {
    // Runs 10 times total, with 3 running in parallel at any moment
    driver.get("https://automateqa.online");
    Assert.assertTrue(driver.getTitle().contains("AutomateQA"));
}

Execution: 3 threads run the method simultaneously. When one finishes, the next invocation starts, until all 10 are done.

invocationCount Only (Sequential)

Java
// Run 5 times — one at a time, sequentially
@Test(invocationCount = 5)
public void repeatTest() {
    System.out.println("Run #" + getCurrentInvocationCount());
    // Use case: verify no memory leak or state corruption over repeated runs
}

threadPoolSize Only (Without invocationCount)

Java
// threadPoolSize without invocationCount = ignored
// invocationCount defaults to 1 — only 1 run
@Test(threadPoolSize = 5) // no effect without invocationCount
public void singleRun() { ... }

API Load Testing Pattern

Java
@Test(invocationCount = 100, threadPoolSize = 10)
public void apiConcurrencyTest() {
    // Simulates 100 concurrent API calls, 10 at a time
    Response response = RestAssured
        .given().baseUri("https://api.automateqa.online")
        .get("/interview-questions");

    Assert.assertEquals(response.getStatusCode(), 200);
    Assert.assertTrue(response.time() < 2000, "Response > 2s");
}

Get Current Invocation Number

Java
@Test(invocationCount = 5, threadPoolSize = 2)
public void trackedTest(ITestContext context) {
    // Track via thread ID
    System.out.println("Thread: " + Thread.currentThread().getId()
        + " | Invocation: " + /* no direct API, use AtomicInteger */ counter.incrementAndGet());
}

private AtomicInteger counter = new AtomicInteger(0);

Use Cases

ScenarioinvocationCountthreadPoolSize
Verify test is not flaky101 (sequential)
Load test API endpoint10020
Check for race conditions5010
Stress test login20025
Verify session isolation205

Important: ThreadLocal Required

With threadPoolSize > 1, multiple threads execute the same method:

Java
@Test(invocationCount = 20, threadPoolSize = 5)
public void parallelSessionTest() {
    // MUST use ThreadLocal driver — 5 threads run this simultaneously
    WebDriver driver = DriverManager.getDriver(); // ThreadLocal
    driver.get("https://automateqa.online");
    Assert.assertNotNull(driver.getTitle());
}

Follow AutomateQA

Related Topics