All Projects → talsma-ict → context-propagation

talsma-ict / context-propagation

Licence: Apache-2.0 License
Propagate snapshots of ThreadLocal values to another thread

Programming Languages

java
68154 projects - #9 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to context-propagation

Rpmalloc
Public domain cross platform lock free thread caching 16-byte aligned memory allocator implemented in C
Stars: ✭ 1,218 (+8020%)
Mutual labels:  thread, concurrency
Sobjectizer
An implementation of Actor, Publish-Subscribe, and CSP models in one rather small C++ framework. With performance, quality, and stability proved by years in the production.
Stars: ✭ 172 (+1046.67%)
Mutual labels:  thread, concurrency
Java Concurrent Programming
📓 《实战Java 高并发程序设计》笔记和源码整理
Stars: ✭ 162 (+980%)
Mutual labels:  thread, concurrency
Mt
tlock, RWMUTEX, Collab, USM, RSem and other C++ templates for Windows to provide read/write mutex locks, various multithreading tools, collaboration, differential updates and more
Stars: ✭ 18 (+20%)
Mutual labels:  thread, concurrency
ComposableAsync
Create, compose and inject asynchronous behaviors in .Net Framework and .Net Core.
Stars: ✭ 28 (+86.67%)
Mutual labels:  thread, concurrency
Rxjava Android Samples
Learning RxJava for Android by example
Stars: ✭ 7,520 (+50033.33%)
Mutual labels:  thread, concurrency
Kommander Ios
A lightweight, pure-Swift library for manage the task execution in different threads. Through the definition a simple but powerful concept, Kommand.
Stars: ✭ 167 (+1013.33%)
Mutual labels:  thread, concurrency
Concurrency
Java 并发编程知识梳理以及常见处理模式 features and patterns
Stars: ✭ 495 (+3200%)
Mutual labels:  thread, concurrency
bascomtask
Lightweight parallel Java tasks
Stars: ✭ 49 (+226.67%)
Mutual labels:  thread, concurrency
YACLib
Yet Another Concurrency Library
Stars: ✭ 193 (+1186.67%)
Mutual labels:  thread, concurrency
Concurrent Programming
🌵《实战java高并发程序设计》源码整理
Stars: ✭ 562 (+3646.67%)
Mutual labels:  thread, concurrency
go-worker-thread-pool
A visual working example of a Thread Pool pattern, based on a known blog article.
Stars: ✭ 24 (+60%)
Mutual labels:  thread, concurrency
React Native Threads
Create new JS processes for CPU intensive work
Stars: ✭ 527 (+3413.33%)
Mutual labels:  thread, concurrency
Threadly
Type-safe thread-local storage in Swift
Stars: ✭ 58 (+286.67%)
Mutual labels:  thread, concurrency
Hamsters.js
100% Vanilla Javascript Multithreading & Parallel Execution Library
Stars: ✭ 517 (+3346.67%)
Mutual labels:  thread, concurrency
Lightio
LightIO is a userland implemented green thread library for ruby
Stars: ✭ 165 (+1000%)
Mutual labels:  thread, concurrency
AtomicKit
Concurrency made simple in Swift.
Stars: ✭ 88 (+486.67%)
Mutual labels:  thread, concurrency
Transmittable Thread Local
📌 TransmittableThreadLocal (TTL), the missing Java™ std lib(simple & 0-dependency) for framework/middleware, provide an enhanced InheritableThreadLocal that transmits values between threads even using thread pooling components.
Stars: ✭ 4,678 (+31086.67%)
Mutual labels:  thread, threadlocal
Java Concurrency Examples
Java Concurrency/Multithreading Tutorial with Examples for Dummies
Stars: ✭ 173 (+1053.33%)
Mutual labels:  thread, concurrency
haxe-concurrent
A haxelib for basic platform-agnostic concurrency support
Stars: ✭ 69 (+360%)
Mutual labels:  thread, concurrency

CI Build Coverage Status Maven Version Javadoc

Context propagation library

Propagate a snapshot of one or more ThreadLocal values into another thread.

This library enables automatic propagation of several well-known ThreadLocal contexts by capturing a snapshot, reactivating it in another thread and ensuring proper cleanup after execution finishes:

Terminology

Context

Abstraction containing a value in the context of a thread. The most common implementation in Java is a ThreadLocal value. The library provies an AbstractThreadLocalContext base class that features nesting values and predictable behaviour for out-of-order closing.

For each context type, there can only be one active context per thread at any time.

ContextManager

Manages a context. The ContextManager API can activate a new context value and provides access to the active context value.

ContextSnapshot

A snapshot contains the current value from all known context managers.
These values can be reactivated in another thread.
Reactivated snapshots must be closed to avoid leaking context.

All context aware utility classes in this library are tested to make sure they reactivate and close snapshots in a safe way.

How to use this library

Capturing a snapshot of ThreadLocal context values

Just before creating a new thread, capture a snapshot of all ThreadLocal context values:

ContextSnapshot snapshot = ContextManagers.createContextSnapshot();

In the code of your background thread, activate the snapshot to have all ThreadLocal context values set as they were captured:

try (Context<Void> reactivation = snapshot.reactivate()) {
    // All ThreadLocal values from the snapshot are available within this block
}

Threadpools and ExecutorService

If your background threads are managed by an ExecutorService, you can use our context aware ExecutorService instead of your usual threadpool.

When submitting new work, this automatically takes a context snapshot to reactivate in the background thread.
After the background thread finishes the snapshot is closed, ensuring no ThreadLocal values leak into the thread pool.

The ContextAwareExecutorService can wrap any ExecutorService for the actual thread execution:

private static final ExecutorService THREADPOOL = 
        new ContextAwareExecutorService(Executors.newCachedThreadpool());

Supported contexts

The following ThreadLocal-based contexts are currently supported out of the box by this context-propagation library:

Custom contexts

Adding your own Context type is possible by creating your own context manager.

Caching

By default the ContextManagers class caches the context manager instances it finds per classloader. Since the cache is per classloader, this should work satisfactory for applications with simple classloader hierarchies (e.g. dropwizard) and also for complex hierarchies (spring boot, JEE and the like).

Disable caching

If however, you wish to disable caching of the context manager instances, you can set either:

  • the java system property talsmasoftware.context.caching, or
  • the environment variable TALSMASOFTWARE_CONTEXT_CACHING

The values false or 0 will disable caching.

Building jars with dependencies

When using a build tool or plugin to create an 'uber-jar', i.e. a jar file with all the classes of its dependencies included, you have to make sure that the service provider configuration files under META-INF/services are either preserved or merged. Otherwise Java's ServiceLoader will not be able to find the context implementations of this library.

In case your are using the Maven Shade Plugin, you can use the ServicesResourceTransformer for this task.

Performance metrics

No library is 'free' with regards to performance. Capturing a context snapshot and reactivating it in another thread is no different. For insight, the library tracks the overall time used creating and reactivating context snapshots along with time spent in each individual ContextManager.

Logging performance

On a development machine, you can get timing for each snapshot by turning on logging for nl.talsmasoftware.context.Timing at FINEST or TRACE level (depending on your logger of choice). Please do not turn this on in production as the logging overhead will most likely have a noticable impact on your application.

Metrics reporting

The context propagation metrics module uses the excellent dropwizard metrics library to instrument Timers for context propagation.

Similarly, the context propagation Micrometer module adds Micrometer instrumentation Timers for the context propagation.

Adding either of these modules to your classpath will automatically configure various timers in the global default metric registry of your application.

License

Apache 2.0 license

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].