ThreadLocal class in Java- purpose and use

According to ThreadLocal class in JavaDoc:

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

I think that its purpose is to bind an object to a thread, which has two distinct and useful effects. The binded object is not shared between other threads, so it can be used without the need for synchronization; It is available in period of the life of thread; also meaning you don’t pass it by method calls.

In real cases, Spring security (by default) does in fact store the user information in a Threadlocal variable, the user information can be accessed (assuming you're executing in the same thread as blowed code:

When to use ThreadLocal

  • To wrap any Non-Thread Safe object in ThreadLocal becomes a thread-safe.
  • To implement per thread context information like Security Context.
  • To preserve or carry information from one method call to another, you can carry it by using ThreadLocal.

ThreadLocal class contains four main methods

  • Object get(): Returns the value in the current thread’s copy of this thread-local variable.
  • set(Object): Sets the current thread’s copy of the thread-local variable to the specified value.
  • Object initialValue(): Returns the current thread’s initial value
  • remove(): Removes the current thread’s value for this thread-local variable.

ThreadLocal Example

I think it really simple, we can avoid costly synchronization when a per thread variable is required.

No comments:

Post a Comment