What is the difference between Thread and ThreadLocal?

Answer by Joshua Engel:

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, ?>

indexed with the current thread, but this is neater and already checked to be thread-safe.

What is the difference between Thread and ThreadLocal?

Advertisements

Leave a comment

Filed under Life

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s