ThreadLocals in Virtual Threads

Swaranga Sarma sarma.swaranga at gmail.com
Mon Jan 4 19:25:33 UTC 2021


I guess my point was not about the ThreadLocal size itself but the fact
that each virtual thread will create a new connection to the database which
might overwhelm the database with too many concurrent connections.

With the current Executor services and behavior of ThreadLocals, I know
that I will never create more than X concurrent connections (where X is the
size of the executor service) even if I have thousands of tests in my suite.

Are there any plans of "processor" local or "carrier thread" local?

Regards
Swaranga


On Mon, Jan 4, 2021 at 11:19 AM Ron Pressler <ron.pressler at oracle.com>
wrote:

> 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