-1

Possible Duplicate:
How is Java’s ThreadLocal implemented under the hood?

It's been a while since I programmed in Java, and I want to freshen up on some theory.

How can I implement my own ThreadLocal from scratch?

Community
  • 1
  • 1
Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
  • What better place to start than [right at the source](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/ThreadLocal.java/). – Marko Topolnik Jan 11 '13 at 10:29
  • It turns out the question is a duplicate. Not sure why down-voted when the previous question has 11 up-votes. – Jasper Blues Jan 11 '13 at 10:42
  • @Peter - heh good point. I thought the question was an interesting one though, and so might be useful to others if it was out in the public domain. – Jasper Blues Jan 11 '13 at 11:01
  • I agree it's an interesting question to answer in a blog for people who are not interested in implementing the details in code but wants an understanding of how it works. You can look at how sub-class ThreadLocal could be useful and what problems it might have. You could also look at InheritableThreadLocal. ;) – Peter Lawrey Jan 11 '13 at 11:05

3 Answers3

2

Yes. You can sub-class thread and copy the implementation in the source for Thread. Or you can just read the code but getting ThreadLocal right is tricky.

There are many tricky elements, the most obvious is preventing memory leaks from threads not being removed.

Even the existing implementation suffers from the issue that sub-classed ThreadLocal objects can prevent ClassLoaders from unloading.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

try this out:

new Thread()
{
    //contents
}.start();

You can spawn this anywhere you want in your code.

Nitesh Verma
  • 1,795
  • 4
  • 27
  • 46
  • 1
    This question does not relate to spawning threads. It relates to ThreadLocal - which is a class for storing information within the context of a running thread, and then retrieving it from some un-related class. . . The internal implementation is quite simple, but I forgot the details, hence asking. – Jasper Blues Jan 11 '13 at 10:50
  • thanks, i have never used ThreadLocal, thought that this might solve your problem. – Nitesh Verma Jan 11 '13 at 16:04
0

It turns out this question is a duplicate:

It's quite simple, really, it's just a Map of name-value pairs stored inside each Thread object (see the Thread.threadLocals field). The API hides that implementation detail, but that's more or less all there is to it.

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185