ThreadLocal api 学习(remove api 是重点)

package com.goods.stock.util;

import com.goods.stock.util.annotation.PayAttention;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.List;

@Slf4j
class ThreadLocalTest {

    private final ThreadLocal userInThreadLocal = new ThreadLocal();


    @Test
    void getApi(){
        final User user = new User(100, "xx", Collections.singletonList(new User(101, "yy", null)));
        userInThreadLocal.set(user);
        assert user == userInThreadLocal.get();
        user.setName("changed");
        assert "changed".equals(userInThreadLocal.get().getName());
    }

    @Test
    void getDefaultApi(){
        final CustomThreadLocal userCustomThreadLocal = new CustomThreadLocal();
        assert null != userCustomThreadLocal.get();
        assert "unKwnUser".equals(userCustomThreadLocal.get().getName());
    }

    @Test
    void setNullApi(){
        final CustomThreadLocal userCustomThreadLocal = new CustomThreadLocal();
        userCustomThreadLocal.set(null);
        try {
            assert "unKwnUser".equals(userCustomThreadLocal.get().getName());
        }catch (Exception e){
            assert e instanceof NullPointerException;
        }
    }

    @Test
    void setRemoveApi1(){
        userInThreadLocal.set(new User());
        userInThreadLocal.remove();
        assert userInThreadLocal.get() == null;
    }

    @Test
    @PayAttention(comment = 
            "1.remove会把(线程,对象)联合对应的map置空; " +
            "2.setNull只会把map里的值置空; " +
            "3.当前请求结束前,应该调用remove,而不是setNull,setNull仍然有内存溢出的风险;"
    )
    void setRemoveApi2(){
        final CustomThreadLocal userCustomThreadLocal = new CustomThreadLocal();
        userCustomThreadLocal.remove();
       //这里不会为空,因为对应的map没了,就会从initValue里面拿默认数据
        assert userCustomThreadLocal.get() != null;

        userCustomThreadLocal.set(null);
        //这里会为空,因为对应的map还在,只是值为空,所有能取到空
        assert userCustomThreadLocal.get() == null;
    }

}

@NoArgsConstructor
@AllArgsConstructor
@Data
class User{
    Integer id;
    String name;
    List children;
}

class CustomThreadLocal extends ThreadLocal {

    @Override
    protected User initialValue(){
       return new User(null,"unKwnUser",null);
    }
}

你可能感兴趣的:(后端开发)