ThreadLocals in Virtual Threads
Ron Pressler
ron.pressler at oracle.com
Mon Jan 4 19:19:37 UTC 2021
Looks fine.
The only thing to consider is that because you have virtual threads, you’re only limited
by your RAM, and so ThreadLocals could, just like any other object, become a footprint
issue. But I see no reason to optimise for that unless footprint becomes your limitation
and your TLs are significant contributors.
— Ron
On 4 January 2021 at 18:12:34, Swaranga Sarma (sarma.swaranga at gmail.com) wrote:
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