---
title: "ThreadLocal  简单分析"
author: "it_like"
date: "2015-01-09T15:21:27Z"
tags: []
categories: ["编程语言"]
slug: "threadlocal"
draft: false
lastmod: "2015-01-09T15:23:01Z"
id: 2174376
url: "https://it-like.iteye.com/blog/2174376"
---

ThreadLocal&lt;T&gt; 是一个泛型类

   protected T initialValue() {   return null;  }// 用于初始化 

```
   private final ThreadLocal<Map<Object, Object>> store;

    public ThreadLocalCache(URL url) {
        this.store = new ThreadLocal<Map<Object, Object>>() {
            @Override
            protected Map<Object, Object> initialValue() {
                return new HashMap<Object, Object>();
            }
        };
    }
```

 

  ThreadLocal 里面有一个ThreadLocalMap class，这个Map通过 Thread的 threadLocalHashCode和nextHashCode 值算出 hashCode 

 

  Thread存储一个字段：保存了ThreadLocalMap 

   t.threadLocals = new ThreadLocalMap(this, firstValue);  // this = ThreadLocal实例

   

   ThreadLocalMap 取值判断

```
   private Entry getEntry(ThreadLocal key) {
            int i = key.threadLocalHashCode & (table.length - 1);
            Entry e = table[i];
            if (e != null && e.get() == key) // 不同的ThreadLocal 即使hashCode一样 也不会取到相同的值   
               return e;
            else 
                return getEntryAfterMiss(key,i,e); 

```

 

    ThreadLocal的remove get set 其实就是对Thread实例的字段操作

 

 附： 别人的代码  

```
public class ThreadLocalCache implements Cache {

    private final ThreadLocal<Map<Object, Object>> store;

    public ThreadLocalCache(URL url) {
        this.store = new ThreadLocal<Map<Object, Object>>() {
            @Override
            protected Map<Object, Object> initialValue() {
                return new HashMap<Object, Object>();
            }
        };
    }

    public void put(Object key, Object value) {
        store.get().put(key, value);
    }

    public Object get(Object key) {
        return store.get().get(key);
    }

}
```