kotlinx.coroutines icon indicating copy to clipboard operation
kotlinx.coroutines copied to clipboard

Add ability to listen for resumption/suspension via a context element

Open dovchinnikov opened this issue 3 years ago • 0 comments
trafficstars

I'm creating a diagnostic tool which collects minimal info about coroutines to be later queried and printed in an acceptable format. I want to collect CoroutineContext, CoroutineStackFrame and current thread, like DebugProbes does.

Problems with DebugProbes:

  • it's applied for all coroutines, even sequence {}, and I only need to trace kotlinx.coroutines;
  • it's either all or nothing, one cannot enable it for a particular coroutine ignoring the rest;
  • it's awfully slow to load (~300ms in our runs, it's noticeable comparing to the whole app startup which takes 2s);
  • it's doing nasty things redefining classes at runtime which is not that of a problem per se, but I'd expect something explicit for a production solution (the main point is to use our tracer in production).

kotlinx.coroutines already has a mechanism for that kind of stuff: ThreadContextElement. I propose to generalize it to the following interface and make internals work with it:

interface ContinuationListener<S> : CoroutineContext.Element { // TBD a better name

  fun beforeResume(cont: Continuation<*>): S

  fun afterSuspend(cont: Continuation<*>, s: S)
}

In this case ThreadContextElement would become a special case of the proposed ContinuationListener. I've checked that Continuation instance is available in all places where ThreadContextElement#updateThreadContext is invoked.

dovchinnikov avatar Aug 18 '22 12:08 dovchinnikov