Sunday, 17 June 2012

What is the difference between thread and threadlocal?

Thread represents the flow of control, i.e. the code that is running as a thread. It can be started, interrupted, waited for, assigned a priority, etc.

ThreadLocal represents a piece of memory attached to the thread. It's a single object that maintains a different value for each thread that uses it. When a thread calls Set on a ThreadLocal, it will get back the same value later, even if other threads have also called set on the same ThreadLocal in the intervening time. Each will get back its own value.

You could achieve the same result with a Map<Thread, ?>, where the current thread is always the key, but this is neater and already checked to be thread-safe.

No comments:

Post a Comment