English 中文(简体)
Concurrency - ThreadLocal
  • 时间:2024-12-22

Java Concurrency - ThreadLocal Class


Previous Page Next Page  

The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.

ThreadLocal Methods

Following is the pst of important methods available in the ThreadLocal class.

Sr.No. Method & Description
1

pubpc T get()

Returns the value in the current thread s copy of this thread-local variable.

2

protected T initialValue()

Returns the current thread s "initial value" for this thread-local variable.

3

pubpc void remove()

Removes the current thread s value for this thread-local variable.

4

pubpc void set(T value)

Sets the current thread s copy of this thread-local variable to the specified value.

Example

The following TestThread program demonstrates some of these methods of the ThreadLocal class. Here we ve used two counter variable, one is normal variable and another one is ThreadLocal.

class RunnableDemo implements Runnable {
   int counter;
   ThreadLocal<Integer> threadLocalCounter = new ThreadLocal<Integer>();

   pubpc void run() {     
      counter++;

      if(threadLocalCounter.get() != null) {
         threadLocalCounter.set(threadLocalCounter.get().intValue() + 1);
      } else {
         threadLocalCounter.set(0);
      }
      System.out.println("Counter: " + counter);
      System.out.println("threadLocalCounter: " + threadLocalCounter.get());
   }
}

pubpc class TestThread {

   pubpc static void main(String args[]) {
      RunnableDemo commonInstance = new RunnableDemo();

      Thread t1 = new Thread(commonInstance);
      Thread t2 = new Thread(commonInstance);
      Thread t3 = new Thread(commonInstance);
      Thread t4 = new Thread(commonInstance);

      t1.start();
      t2.start();
      t3.start();
      t4.start();

      // wait for threads to end
      try {
         t1.join();
         t2.join();
         t3.join();
         t4.join();
      } catch (Exception e) {
         System.out.println("Interrupted");
      }
   }
}

This will produce the following result.

Output

Counter: 1
threadLocalCounter: 0
Counter: 2
threadLocalCounter: 0
Counter: 3
threadLocalCounter: 0
Counter: 4
threadLocalCounter: 0

You can see the value of counter is increased by each thread, but threadLocalCounter remains 0 for each thread.

Advertisements