ThreadLocals in Virtual Threads
Swaranga Sarma
sarma.swaranga at gmail.com
Mon Jan 4 18:11:47 UTC 2021
Hello,
What is the guidance of using ThreadLocal variables under virtual threads.
One of the ways in which we use it is integration tests - we use
ThreadLocal containers to scope a variable to a single test while still
being able to run tests in parallel. For instance:
class SampleIntegrationTest {
private final ThreadLocal<Connection> connection = new ThreadLocal<>();
@BeforeEach
public void setup() {
connection.set(createNewConnection());
}
@AfterEach
public void teardown() {
connection.get().close();
}
@Test
public void testA() {
// use database connection
}
@Test
public void testB() {
// use database connection
}
...
}
In the above, I can run both Test A and B in parallel, without interfering
with each other. If these tests were run with traditional Thread pools, I
know that no more than 'X' connections will be opened to the database at a
time where 'X' is the number of threads I configure the test execution
engine with. However, with virtual threads, I will have no control over how
many Threads will be created (may be one for each test) and that might
overwhelm the databases.
Would you say this is the wrong usage of ThreadLocals with virtual threads?
An alternative would be to move this management of the connections to the
test code itself with semaphores/connection-pools etc.
Thoughts?
Regards
Swaranga
More information about the loom-dev
mailing list