Class HighLite ThreadLocal

Some people think that by not using threads that would make their code thread safe. One way to write thread safe code is to pass state by parameters as much as possible, limit the use of singletons (also a source of memory leaks), syncronize accordingly, and use ThreadLocal objects where appropriate.

The ThreadLocal class is an object container that can store a different object for each thread where it is used. I think of the the ThreadLocal as a HashMap where each thread can set/get it’s own object, where implicitly the key for that object is the thread itself. To create a new ThreadLocal you can do the following:

[source:java]
ThreadLocal counter = new InheritableThreadLocal();
[/source]

Now to get and set the object stored in the counter ThreadLocal and we can do something like:

[source:java]
Integer count = (Integer)counter.get();
if(count == null)
count.set(new Integer(1));
else
count.set(new Integer(count.intValue() + 1);
[/source]

Technorati Tags: , , ,