线程特有存储模式(Thread Specific Storage)

来源:互联网 发布:淘宝上整点抢商品技巧 编辑:程序博客网 时间:2024/06/04 18:54

八、线程特有存储模式(Thread Specific Storage)
1、核心思想
通过不共享变量实现了线程安全,避免了与锁的消耗及相关的问题。每个线程都有且只持有一个变量实例
2、适用场景
a、需要使用非线程安全对象,但又不希望引入锁。
b、使用线程安全对象,但希望避免其使用的锁的开销和相关问题。
c、隐式参数传递:他是线程全局可见的
d、特定于线程的单例模式,希望每个线程有且仅有该类的一个实例。
3、线程池环境下使用该模式
同一个线程可能处理多个任务,此时需要考虑在适当的时间和地方清理线程特有对象。

/** * 线程上下文全局变量 * @author huzhiqiang * */public class ThreadContent {    private static ThreadLocal<String> threadLocal = new ThreadLocal<String>();    public static String getThreadLocal() {        return threadLocal.get();    }    public static void setThreadLocal(String value) {        ThreadContent.threadLocal.set(value);    }}public class ThreadSpecificSecureRandom {    //该类的唯一实例    public static final ThreadSpecificSecureRandom INSTANCE = new ThreadSpecificSecureRandom();    private static final ThreadLocal<SecureRandom> secureRandom = new ThreadLocal<SecureRandom>(){        //初始化返回对象        protected SecureRandom initialValue() {            SecureRandom srnd;            try {                srnd = SecureRandom.getInstance("SHA1PRNG");            } catch (NoSuchAlgorithmException e) {                e.printStackTrace();                srnd = new SecureRandom();            }            return srnd;        }    };    private ThreadSpecificSecureRandom(){    }    public int nextInt(int upperBound){        SecureRandom srnd = secureRandom.get();        return srnd.nextInt(upperBound);    }    public void setSeed(long seed){        SecureRandom s = secureRandom.get();        s.setSeed(seed);    }}
0 0
原创粉丝点击