Make delicious recipes!

ThreadLocal <T>

    ThreadLocal is used to automatically create copy of a variable for every thread. For example, in a web server, if every thread needs a unique identifier then we can use a variable like:


class UniqueId {

    static int count = 0;

    static ThreadLocal  idForEachThread = new ThreadLocal  () {
        private Integer initialValue () {
            return count++;
        }
    }

    static public int getUniqueId () { return idForEachThread.get(); }
}


Now, every thread can call UniqueId.getUniqueId () and for every thread that calls this method, a new instance of idForEachThread is created.This makes sure that every thread has its own unique copy of the integer and that one thread cannot overwrite the other thread’s value.



Advantage of having unique copy per thread is that the above method becomes thread aware automatically. For example, if a method calls getUniqueId() it will get id for its own thread but the same method running concurrently for another thread will get id for its own thread from this function.

So, one can think of ThreadLocal’s internal implementation as a hash-map whose key is the thread itself and value is the value of the variable-reference corresponding to that thread.


Another related interesting class is InheritableThreadLocal where the value of the variable is different across threads at the same level but same across child threads i.e. child threads basically share the variable from the parent.

Normally the child's values will be identical to the parent's; however, the child's value can be made an arbitrary function of the parent's value by overriding the childValue method in this class.

protected Object childValue (Object parentValue);




Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal