Java ThreadLocal Class



Introduction

The Java ThreadLocal class provides thread-local variables.

Class Declaration

Following is the declaration for java.lang.ThreadLocal class −

public class ThreadLocal<T>
   extends Object

Class constructors

Sr.No. Constructor & Description
1

ThreadLocal()

This creates a thread local variable.

Class methods

Sr.No. Method & Description
1 T get()

This method returns the value in the current thread's copy of this thread-local variable.

2 protected T initialValue()

This method returns the current thread's "initial value" for this thread-local variable.

3 void remove()

This method removes the current thread's value for this thread-local variable.

4 void set(T value)

This method sets the current thread's copy of this thread-local variable to the specified value.

Methods inherited

This class inherits methods from the following classes −

  • java.lang.Object

Example: Getting a Value from ThreadLocal Object

The following example shows the usage of Java ThreadLocal get() method. In this program, we've initialized a ThreadLocal object. Using set() method, a value is assigned to ThreadLocal object and using get() method, value is retrieved and printed.

package com.tutorialspoint;

public class ThreadLocalDemo {

   public static void main(String[] args) {

      ThreadLocal<Integer> tlocal = new ThreadLocal<Integer>();  

      tlocal.set(100);
      // returns the current thread's value
      System.out.println("value = " + tlocal.get());
 
      tlocal.set(90);
      // returns the current thread's value of 
      System.out.println("value = " + tlocal.get());
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

value = 100
value = 90
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy