img
. . .
Example 8-4 Using ThreadLocal in Java
public MyObject {
static ThreadLocal transcendental = new ThreadLocal();
}
public MyRunnable implements Runnable {
public void run() {
MyObject.transcendental.set(new Float(3.1415926535));
...
bar();
}
public void bar () {
meditateOn((Float) MyObject.transcendental.get());
}
}
Thread t = new Thread(new Myrunnable());
t.start();
You still have the problem of figuring out how to pass the ThreadLocal object around. Here, we
have chosen to make it a static instance variable of MyObject. When you are creating all the
threads yourself, you can use the first method, subclassing Thread, but when you are using
threads that someone else created, you will need to use thread local storage. Clearly, any kind of
TSD is going to be slower than accessing simple global variables. Note that the current
performance of ThreadLocal is significantly worse than using our home-built thread-local
variables! (See Timings.)
The other missing piece of functionality is the lack of a specific TSD destructor. The primary use
of a TSD destructor in POSIX is to reclaim dynamically allocated data, something the Java
garbage collector will do automatically. The other, more general use of a destructor is to return a
specific resource (e.g., to replace an object onto a list of free objects, close a file descriptor, socket,
etc.). There is no direct parallel for this in Java. If you find yourself with this kind of problem
(very unlikely!), you will need to write an ad hoc method to take care of it at thread exit time.
Should you wish to know what Runnable your thread is, you can use a thread local variable or
thread local storage to record that information (Code Examples 8-5 and 8-6).
Example 8-5 Recording the Runnable in the Thread
public class MyThread extends Thread {
Runnable runnable;
public MyThread(Runnable r) {
super(r);
runnable = r;
}
}
Example 8-6 Recording the Runnable in Thread Local Storage
public class MyThread extends Thread {
static ThreadLocal runnable = new ThreadLocal();
public MyThread(Runnable r) {
super(r);
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home