tony
tony

Reputation: 137

About the internal design of "ThreadLocal"

I just researched the source code of Java ThreadLocal,I have two questions, hope you can help me!

First,why not just use one Map to store all values, instead of binding the map to a thread? Like this:

public class ThreadLocal<T> {

    private ConcurrentHashMap<Thread, T> threadAndVal = new ConcurrentHashMap<>(); 

    // get value from threadAndVal.... put value to threadAndVal
}

And in method set(T value), I didn't see any synchronization strategy. Is this thread-safe?

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);  // ⬅️Why createMap is thread safe?
    }

Thank you for your help!

Upvotes: 1

Views: 74

Answers (1)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147124

Why not use a ConcurrentHashMap?

The primary reason is performance. Using a thread-safe map is significantly slower than using a custom map without thread-safety.

The secondary reason is that a Map<Thread,T> would keep a reference to both the thread and value for as long as the ThreadLocal exists, and they are often used as statics.

A fun third reason is that I can create a Thread with overridden equals and hashCode that behaves naughtily.

Is ThreadLocal.set thread-safe?

It doesn't need to be. The first line is:

Thread t = Thread.currentThread();

Everything else is done on the Thread t. All of these operation can only be done from that exact thread.

Upvotes: 3

Related Questions