0

And I haven't found a way to replicate it.

So I have a ThreadLocal storing a Map<String,String> whose initial value is an empty map.

I'm checking at the beginning of every HTTP Request, and unpredictably that ThreadLocal may be storing a non empty map, with values from another previous request.

I'm using the following construct:

withContext(threadLocal.asContextElement(someMap)){...}

How can I fix it?

caeus
  • 3,084
  • 1
  • 22
  • 36
  • Does this help? https://stackoverflow.com/questions/46227462/how-to-use-code-that-relies-on-threadlocal-with-kotlin-coroutines/46227463 – dnault Jun 13 '23 at 18:58
  • If the thread was used by a previous request, then of course the `ThreadLocal` will keep whatever changes were done, using it as a context element doesn't automatically clear it when you exit `withContext`. – Alexis Jun 13 '23 at 19:59

1 Answers1

0

The parent coroutine context for all requests can be configured when starting the ktor server.

When creating the embedded server multiple helper methods can be used. The most commonly used, however, passes an EmptyCoroutineContext, and so that one cannot be used.

I used

public fun <TEngine : ApplicationEngine, TConfiguration : ApplicationEngine.Configuration>
CoroutineScope.embeddedServer(
    factory: ApplicationEngineFactory<TEngine, TConfiguration>,
    vararg connectors: EngineConnectorConfig = arrayOf(EngineConnectorBuilder()),
    watchPaths: List<String> = listOf(WORKING_DIRECTORY_PATH),
    parentCoroutineContext: CoroutineContext = EmptyCoroutineContext,
    configure: TConfiguration.() -> Unit = {},
    module: Application.() -> Unit
): TEngine

insead.

Ej:


 GlobalScope.embeddedServer(
                Netty,
                port = config.port,
                parentCoroutineContext = myThreadLocal.asContextElement()
            ) {
                ...
            }

caeus
  • 3,084
  • 1
  • 22
  • 36