Java Reference
In-Depth Information
Thread-Local Variables
A thread-local variable provides a way to maintain a separate value for a variable for each thread. The
ThreadLocal
class in the
java.lang
package provides the implementation of a thread-local variable. It has four methods:
get()
,
set()
,
remove()
, and
initialValue()
. The
get()
and
set()
methods are used to get and set the value for a
thread-local variable, respectively. You can remove the value by using the
remove()
method. The
initialValue()
method is used to set the initial value of the variable, and it has a
protected
access. To use it, you need to subclass the
ThreadLocal
class and override this method.
Let's create a
CallTracker
class, shown in Listing 6-60, to keep track of the number of time times a thread calls
its
call()
method.
Listing 6-60.
A Class That Uses a ThreadLocal Object to Track Calls to Its Method
// CallTracker.java
package com.jdojo.threads;
public class CallTracker {
// threadLocal variable is used to store counters for all threads
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
public static void call() {
int counter = 0 ;
Integer counterObject = threadLocal.get();
if (counterObject == null) {
counter = 1;
}
else {
counter = counterObject.intValue();
counter++;
}
// Set the new counter
threadLocal.set(counter);
// Print how many times this thread has called this method
String threadName = Thread.currentThread().getName();
System.out.println("Call counter for " + threadName + " = " + counter);
}
}
The
get()
method of the
ThreadLocal
class works on a thread basis. It returns the value set by the
set()
method
by the same thread, which is executing the
get()
method. If a thread calls the
get()
method the very first time, it
returns
null
. The program sets the call counter for the caller thread to 1 if it is its first call. Otherwise, it increments the
call counter by 1. It sets the new counter back in the
threadLocal
object. At the end of the call, you print a message
about how many times the current thread has called this method.
Listing 6-61 uses the
CallTracker
class in three threads. Each thread calls this method a random number of
times between 1 and 5. You can observe in the output that the counter is maintained for each thread's call separately.