美文网首页
由StringCoding源码联想到ThreadLocal的那些

由StringCoding源码联想到ThreadLocal的那些

作者: huangxiongbiao | 来源:发表于2018-10-26 09:59 被阅读24次
1、StringCoding源码

主要说明 static char[] decode(String charsetName, byte[] ba, int off, int len)方法
此方法为静态方法,单线程会判断StringDecoder不存在或编码不一致是生成一个新的StringDecoder来处理编码没有bug。如果多线程只有一个StringDecoder对象那么解码方法会冲突导致编码转化错误。如果利用对象方法则会生成过多对象影响效率,此时就用到了ThreadLocal,为每一个线程生成一个独立的StringDecoder对象避免该问题

static char[] decode(String charsetName, byte[] ba, int off, int len)
        throws UnsupportedEncodingException
    {
        StringDecoder sd = deref(decoder);
        String csn = (charsetName == null) ? "ISO-8859-1" : charsetName;
        if ((sd == null) || !(csn.equals(sd.requestedCharsetName())
                              || csn.equals(sd.charsetName()))) {
            sd = null;
            try {
                Charset cs = lookupCharset(csn);
                if (cs != null)
                    sd = new StringDecoder(cs, csn);
            } catch (IllegalCharsetNameException x) {}
            if (sd == null)
                throw new UnsupportedEncodingException(csn);
            set(decoder, sd);
        }
        return sd.decode(ba, off, len);
    }

下面代码是ThreadLocal的使用给ThreadLocal赋值和取值

private StringCoding() { }

    /** The cached coders for each thread */
    private final static ThreadLocal<SoftReference<StringDecoder>> decoder =
        new ThreadLocal<>();
    private final static ThreadLocal<SoftReference<StringEncoder>> encoder =
        new ThreadLocal<>();

    private static boolean warnUnsupportedCharset = true;

    private static <T> T deref(ThreadLocal<SoftReference<T>> tl) {
        SoftReference<T> sr = tl.get();
        if (sr == null)
            return null;
        return sr.get();
    }

    private static <T> void set(ThreadLocal<SoftReference<T>> tl, T ob) {
        tl.set(new SoftReference<T>(ob));
    }

2、ThreadLocal源码解读

参考:http://www.cnblogs.com/dolphin0520/p/3920407.html
https://blog.csdn.net/puppylpg/article/details/80433271

主要方法

从get,set中我们可以看到Thread 对象拥有一个ThreadLocalMap,set的值保存在ThreadLocalMap内。每个thread有一个ThreadLocalMap,而ThreadLocalMap保存了实际set的值以此实现线程封闭值。引用关系为
thread强引用ThreadLocalMap,ThreadLocalMap拥有Entry,Entry中的key弱引用ThreadLoca了,值为set的值

引用关系
  public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

ThreadLocalMap的源码我们可以看到firstKey的值为ThreadLocal
Entry的实例化方法弱引用的ThreadLocal。疑问:entry弱引用ThreadLocal和强引用对于entry的释放没有任何用处,此处的弱引用是用来防止ThreadLocal的gc不及时吗?但是ThreadLocal好像但是用的static对于此处的弱引用心存怀疑

 static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }


 ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }

 public WeakReference(T referent) {
        super(referent);
    }
3、ThreadLocalMap中为什么Entry对ThreadLocal使用弱引用分析

其原因是为了当ThreadLocal被释放回收时,能够及时的回收ThreadLocal和entry。如果此处为强引用,ThreadLocal同时会有两个强引用链条,就算将ThreadLocal设置为null,entry对其也有着强引用会导致ThreadLocal和entry都不能及时释放。此时使用弱引用可以保证ThreadLocal设置为null时及时被gc,而ThreadLocalMap中对于entry实现了自己的回收机制,当ThreadLocal为null时,ThreadLocalMap进行rehash时会掉用expungeStaleEntries方法对老旧的entry进行回收。回收的条件是ThreadLocal为null。代码如下e.get() == null获取的对象是ThreadLocal本身

 private void rehash() {
            expungeStaleEntries();

            // Use lower threshold for doubling to avoid hysteresis
            if (size >= threshold - threshold / 4)
                resize();
        }

/**
         * Expunge all stale entries in the table.
         */
        private void expungeStaleEntries() {
            Entry[] tab = table;
            int len = tab.length;
            for (int j = 0; j < len; j++) {
                Entry e = tab[j];
                if (e != null && e.get() == null)
                    expungeStaleEntry(j);
            }
        }

private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // expunge entry at staleSlot
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // Rehash until we encounter null
            Entry e;
            int i;
            for (i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    size--;
                } else {
                    int h = k.threadLocalHashCode & (len - 1);
                    if (h != i) {
                        tab[i] = null;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }

ps:此处对于弱引用的使用场景有一个小小的感悟,当一个对象同时拥有两条或多条强引用链条时,而只有一条强引用链条是我们真正关心和使用的(即这条链条释放就想及时gc该对象)。我们可以选择这一天一条链条使用强引用其余的链条使用弱引用避免内存不能够及时gc。

相关文章

网友评论

      本文标题:由StringCoding源码联想到ThreadLocal的那些

      本文链接:https://www.haomeiwen.com/subject/efxktqtx.html