Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.5k points)

When should I use a ThreadLocal variable?

How is it used?

1 Answer

0 votes
by (46k points)

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

For example, the class below creates unique identifiers local to each thread. A thread's id is indicated the first time it invokes ThreadId.get() and remains stable on subsequent calls.

 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {

     private static final AtomicInteger nextId = new AtomicInteger(0);

     private static final ThreadLocal<Integer> threadId =

         new ThreadLocal<Integer>() {

             @Override protected Integer initialValue() {

                 return nextId.getAndIncrement();

         }

     };

     public static int get() {

         return threadId.get();

     }

 }

Each thread operates an implicit reference to its image of a thread-local variable as long as the thread is running and the ThreadLocal instance is available; after a thread goes away, all of its copies of thread-local cases are subject to garbage collection (except other references to these copies exist).

 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 23, 2020 in Python by sabarish (200 points)

Browse Categories

...