Interface ExecutionContextManager
-
- All Implemented Interfaces:
public interface ExecutionContextManagerHolds and exposes information about current execution context in a thread-local storage
-
-
Method Summary
Modifier and Type Method Description abstract <T extends Any> TgetFromCurrentContext(String key)abstract UnitpushToContext(String key, Object value)This method and popFromContext do the same thing as withContext, it's highly recommended to use them as below:
These methods are introduced in order to avoid new lambda object construction during frequent calls to withContext.pushToContext(myKey, myValue) try { // action } finally { popFromContext(myKey) }abstract UnitpopFromContext(String key)abstract Map<String, Object>getCurrentContext()Exposes current context which is configured via previous pushToContext calls. abstract CoroutineContextgetCurrentCoroutineContextElements()Exposes all current context information as CoroutineContext. -
-
Method Detail
-
getFromCurrentContext
abstract <T extends Any> T getFromCurrentContext(String key)
-
pushToContext
abstract Unit pushToContext(String key, Object value)
This method and popFromContext do the same thing as withContext, it's highly recommended to use them as below:
pushToContext(myKey, myValue) try { // action } finally { popFromContext(myKey) }These methods are introduced in order to avoid new lambda object construction during frequent calls to withContext.
Note: it's recommended to use withContext whenever possible as it guarantees that target data is popped out from active context once target action is done. This explicit push/pop operations are only for situations when we fine-tune application to avoid memory consumption as much as possible.
-
popFromContext
abstract Unit popFromContext(String key)
-
getCurrentContext
abstract Map<String, Object> getCurrentContext()
Exposes current context which is configured via previous pushToContext calls.
Essentially it returns aggregation of getFromCurrentContext results for all registered context keys.
-
getCurrentCoroutineContextElements
abstract CoroutineContext getCurrentCoroutineContextElements()
Exposes all current context information as CoroutineContext.
Currently execution context is based on thread and ThreadLocal but different coroutines can be executed on different threads.
If we want to keep using currentContext data in coroutines, we should include currentCoroutineContextElements as part of coroutine context, for example, as below:
runBlocking { launch(Dispatchers.IO + executionContextManager.currentCoroutineContextElements) { // coroutine logic } }
-
-
-
-