Skip to content

Expose isNewCoroutine from CopyableThreadContextElement #3902

Open
@wanyingd1996

Description

@wanyingd1996

Use case

Hi, all. Our tracing system is based on ThreadLocal. To not lose changes to our ThreadLocal, we store the object in CopyableThreadContextElement.

ThreadLocal.set(trace)
withContext(context) { // copyForChild()
  // updateThreadContext()
  assertThat(ThreadLocal.get()).isEqualTo(trace)
  ...
}

class TraceThreadContextElement(val trace: Trace) {
  fun copyForChild() {
    return TraceThreadContextElement(ThreadLocal.get())
  }

  fun updateThreadContext() {
    ThreadLocal.set(trace)
  }
}

The above solution works fine for us, but we only want to propagate our object when used with withContext, we don't want to propagate the state into launch, because we as a tracing system, only consider withContext as part of the execution of the enclosing code block, since it is blocking, while launch is not.

Therefore, we hope there is a way to tell whether the CopyableThreadContextElement is created for withContext or launch, and I noticed coroutine implementation already has a boolean isNewCoroutine indicating the difference, and I wonder if is possible to expose this flag from copyForChild, thanks!

The Shape of the API

interface CopyableThreadContextElement {
  fun copyForChild(isNewCoroutine: Boolean)
  fun mergeForChild(isNewCoroutine: Boolean)
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions