. .
key = TlsAlloc();
TlsSetValue(key, data);
data = TlsGetValue(key);
The actual implementation of TSD is different from vendor to vendor, but in general they're all the
same. When accessing a TSD item, we first need to know which thread we're running on. Think
about this for a moment. How does a thread find out who it is? How does it find its own thread
structure? On SPARC machines, there is one register (g7) reserved for special use. Compiler
writers are instructed not to use it. Here the threads library places a pointer to the thread structure
of the running thread. The thread first dereferences g7 to find the structure [this is what
pthread_self() and Thread.currentThread() do], then it dereferences an element of
the structure to find the TSD array. Finally, it looks up the appropriate element in the array.
Java TSD
Java did not provide for TSD directly until Java 2. This was not a problem, however, as the ability
to extend the thread class meant that you could simply add an instance variable to a subclass if you
were in control of thread creation (Code Example 8-3).
This technique is fairly straightforward, efficient, and gives you most of the functionality that
POSIX TSD does. It does require you to declare the TSD as part of the thread, versus the more
dynamic nature of POSIX TSD, but this is unlikely to be a problem. (In this simple example we do
not provide any protection to ensure that only the current thread can access the TSD, but clearly
no other thread should.)
Example 8-3 Implementing TSD by Subclassing Thread
public MyThread extends Thread {
float transcendental;
public MyRunnable implements Runnable {
public run() {
((MyThread)Thread.currentThread()).transcendental =
public bar () {
Thread t = new MyThread(new Myrunnable());
Nonetheless, in Java 2, a TSD class (actually called TLS-- thread local storage) is provided that
will give you a more dynamic, POSIX-like functionality (Code Example 8-4). In this version you
create an instance of the ThreadLocal class, then when you call the set() and get() methods,
you will be manipulating a thread-specific value. This is essentially just a hash table indexed on
the current thread. The values stored by ThreadLocal do need to be of type Object, so
primitive types must be contained in the appropriate wrapper type (e.g., Integer for int).
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks