Skip to content

Test Performance: Avoid repeatedly creating ExecutorService in ExpectTest (RCTP) #1624

@QiuYucheng2003

Description

@QiuYucheng2003

I have analyzed the source code of core/src/test/java/com/google/common/truth/ExpectTest.java and identified a potential performance improvement regarding thread pool usage.

Currently, several test methods instantiate their own ExecutorService (via newFixedThreadPool or newSingleThreadExecutor) and shut it down at the end of the method.

Locations:
Line 187 (in bash method): ExecutorService executor = newFixedThreadPool(10);

Line 198 (in failWhenCallingThatAfterTest method): ExecutorService executor = newSingleThreadExecutor();

Line 211 (in failWhenCallingFailingAssertionMethodAfterTest method): ExecutorService executor = newSingleThreadExecutor();

Analysis (RCTP - Repeatedly Create Thread Pool) Initializing a new thread pool for each test execution incurs the overhead of thread creation, OS resource allocation, and subsequent teardown. While this provides test isolation, it contributes to slower test suite execution times, specifically due to the context switching and initialization costs associated with ThreadPoolExecutor.

If these tests are run frequently (e.g., in CI/CD pipelines or as part of a larger suite), this overhead accumulates.
Suggested Improvement Consider refactoring ExpectTest to use a shared ExecutorService instance. This could be achieved by:

  1. Initializing a static ExecutorService in a @BeforeClass method.
  2. Shutting it down in an @afterclass method.

This approach would reuse threads across the test methods (bash, failWhenCallingThatAfterTest, etc.), reducing the I/O and CPU overhead associated with repeated thread pool creation.

Code Example (Current vs Suggested):

Current:
@test
public void bash() throws Exception {
ExecutorService executor = newFixedThreadPool(10); // Created every time
// ...
executor.shutdown();
}

Suggested:
private static ExecutorService sharedExecutor;

@BeforeClass
public static void setupExecutor() {
sharedExecutor = Executors.newFixedThreadPool(10);
}

@afterclass
public static void teardownExecutor() {
sharedExecutor.shutdown();
}

@test
public void bash() throws Exception {
// Use sharedExecutor
}

Environment
Component: truth-core tests
File: ExpectTest.java

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions