ThreadLocal实战和原理探索

自己写的课程案例,备份一下。

一、课程介绍
掌握ThreadLocal的作用和用法,熟悉使用场景,探索原理。

二、作用
存储线程范围内的信息。
Thread中有ThreadLocal的内部类ThreadLocalMap,里面维护一个Entry数组,Entry中存储ThreadLocal和对应值。

三、用法
@Slf4j
public class ThreadLocalUseTest {

@Test
public void test() {
    ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
    threadLocal.set(1);
    Thread.currentThread();
    threadLocal.get();

    threadLocal = ThreadLocal.withInitial(() -> 2);
}

}

四、应用场景
(1)线程隔离式的单例
1>自定义
public class ThreadLocalSingleton {

private static final ThreadLocal<Singleton> LOCAL = ThreadLocal.withInitial(Singleton::new);

private ThreadLocalSingleton() {
}

public static Singleton getInstance() {
    return LOCAL.get();
}

}

2>在Mybatis中的实践
依赖:

org.mybatis
mybatis
3.2.3

ErrorContext建立:
package org.apache.ibatis.executor;

public class ErrorContext {

private static final ThreadLocal LOCAL = new ThreadLocal();

private ErrorContext() {
}

public static ErrorContext instance() {
ErrorContext context = LOCAL.get();
if (context == null) {
context = new ErrorContext();
LOCAL.set(context);
}
return context;
}

}
ErrorContext使用:
存放上当前线程各个地方遇到的信息,打印错误时可以汇总这些信息。
package org.apache.ibatis.executor;

public abstract class BaseExecutor implements Executor {

public int update(MappedStatement ms, Object parameter) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity(“executing an update”).object(ms.getId());
return doUpdate(ms, parameter);
}

@SuppressWarnings(“unchecked”)
public List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity(“executing a query”).object(ms.getId());
return list;
}

}
(2)上下文模式的生产实践
1> 阿里和滴滴的实践
pupublic class UserContext {

private static final ThreadLocal<UserContext> LOCAL = ThreadLocal.withInitial(UserContext::new);

private User user;

public static UserContext instance() {
    return LOCAL.get();
}

public void setUser(User user) {
    this.user = user;
}

public User getUser() {
    return this.user;
}

}

public class LoginInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
User user = getUser();
request.setAttribute("user", user);

    dealUserContext(request);
    return true;
}

private void dealUserContext(HttpServletRequest request) {
    User user = getUser();
    UserContext.instance().setUser(user);
}

private User getUser() {
    // 根据SessionId从Redis中找到用户
    return new User();
}

}

public class UserContextDemoServiceImpl implements IUserContextDemoService {

@Override
public void userContextDemo() {
    part1();
}

private void part1() {
    part1_1();
    part1_2();
}

private void part1_1() {
}

private void part1_2() {
    UserContext.instance().getUser();
}

}

3>支付中台的实践
ppublic class PayContext {

private static ThreadLocal<PayContext> LOCAL = ThreadLocal.withInitial(PayContext::new);

private Pay pay;

private PayContext() {
}

public static PayContext instance() {
    return LOCAL.get();
}

public Pay getPay() {
    return pay;
}

public void setPay(Pay pay) {
    this.pay = pay;
}

}

private void dealPayContext(HttpServletRequest request) {
String requestURI = request.getRequestURI();
PayType payType = null;
if(requestURI.startsWith(“/order/”)) {
payType = PayType.TICKET;
} else if(requestURI.startsWith(“/coupon/”)){
payType = PayType.COUPON;
}

Pay pay = new Pay();
pay.setPayType(payType);
PayContext.instance().setPay(pay);

}

p// 票和优惠券的支付、退款逻辑相同,只是不同的表,涉及表的方法,根据上下文存储的类型判断,直接读写不同的表,不需要改动上一层的方法传参
Pay pay = PayContext.instance().getPay();
PayType payType = pay.getPayType();
if(PayType.TICKET == payType) {
// 读写支付票的订单表、配置表、回调表、退款表
} else if(PayType.COUPON == payType) {
// 读写支付优惠券的订单表、配置表、回调表、退款表
}
}

五、原理
(1)线性探测
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}

private void set(ThreadLocal<?> key, Object value) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);

for (Entry e = tab[i];
     e != null;
// 从计算出的索引位开始,依次查找相同的ThreadLocal,是使用线性探测的方式解决哈希冲突
     e = tab[i = nextIndex(i, len)]) {
    ThreadLocal<?> k = e.get();

    if (k == key) {
        e.value = value;
        return;
    }

    if (k == null) {
        replaceStaleEntry(key, value, i);
        return;
    }
}

tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
    rehash();

}

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();
}

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

private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
// 第一个索引位的Entry的key是对应查找ThreadLocal就返回
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}

private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
Entry[] tab = table;
int len = tab.length;

while (e != null) {
    ThreadLocal<?> k = e.get();
    if (k == key)
        return e;
    if (k == null)
        expungeStaleEntry(i);
    else
// 依次查找下一个
        i = nextIndex(i, len);
    e = tab[i];
}
return null;

}

public
class Thread implements Runnable {
// 线程中对应有ThreadLocalMap
ThreadLocal.ThreadLocalMap threadLocals = null;
}

(2)弱引用
static class ThreadLocalMap {

// ThreadLocal不被其它地方使用,应该被回收时,就会被回收,不会因为线程存在,线程使用了ThreadLocalMap,ThreadLocalMap中有这个ThreadLocal而无法回收,所以使用弱引用可以防止内存泄露
static class Entry extends WeakReference<ThreadLocal<?>> {
    /** The value associated with this ThreadLocal. */
    Object value;

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

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

tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;

Entry e;
int i;
for (i = nextIndex(staleSlot, len);
     (e = tab[i]) != null;
     i = nextIndex(i, len)) {
    ThreadLocal<?> k = e.get();
    if (k == null) {

// ThreadLocal被回收,对应的value和Entry也应该被回收
e.value = null;
tab[i] = null;
size–;
} else {
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab[i] = null;
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}

六、总结
ThreadLocal可以存储线程的信息,在框架和实际生产中有关键的作用,需要熟练掌握用法和使用场景。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风铃峰顶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值