Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Last active August 29, 2023 13:27
Show Gist options
  • Save ariesmcrae/d14dae20a5e243968584c894446d07ad to your computer and use it in GitHub Desktop.
Save ariesmcrae/d14dae20a5e243968584c894446d07ad to your computer and use it in GitHub Desktop.
Java ThreadLocal vs Node.js AsyncLocalStorage vs Python contextvars

How to store data within the request context using ThreadLocal (java), AsyncLocalStorage (node.js) vs contextvars (python)

Java's ThreadLocal

  • ThreadLocal is a class in Java that allows you to create variables that can only be read and written by the same thread. Even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads can't see each other's ThreadLocal variables. So, it's a form of thread confinement which is useful for preventing thread-safety issues.
  • The primary limitation of ThreadLocal is that it is specifically tied to thread-based parallelism, so it's not as useful in event-driven or asynchronous programming models.

Python's contextvars

  • The contextvars module in Python 3.7+ provides a way to manage context-specific variables in a way that is more flexible than ThreadLocal, and specifically designed to work well with asynchronous tasks. The ContextVar class represents a variable that has different values depending on the context in which it is accessed.
  • Unlike ThreadLocal, contextvars work well with Python's asyncio library, which is used for asynchronous I/O bound tasks.
  • A potential downside of contextvars is that it requires Python 3.7 or later, so it's not available in older Python versions.

Node.js AsyncLocalStorage

  • AsyncLocalStorage in Node.js is similar to Python's contextvars, but designed to work with JavaScript's event-driven, asynchronous programming model. It allows you to store data that can be accessed throughout the lifecycle of a request or operation, even across async operations and callbacks.
  • AsyncLocalStorage is a class in the 'async_hooks' module, which provides an API for tracking the state of asynchronous resources in a Node.js application. An instance of AsyncLocalStorage represents a storage that carries data throughout the execution of asynchronous operations.
  • One key difference is that Node.js does not have a thread-based parallelism model like Java or Python (since JavaScript is single-threaded), so AsyncLocalStorage is not really comparable to Java's ThreadLocal. It's more similar to Python's contextvars, but designed to work in a single-threaded, event-driven context.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment