ThreadLocal的实现原理

调用者:

private static ThreadLocal s_doneCode = new ThreadLocal();
	
	public static long getDoneCode() {
		Long done_code = (Long)s_doneCode.get();
	    if (done_code == null) {
	    	long doneCode = 100000000000000L;
	    	doneCode = doneCode + ServiceManager.getDoneCode();//这里是取的getNewId,不用考虑同步问题
	    	done_code = new Long(doneCode);
	    	s_doneCode.set(done_code);
	    }
	    return done_code.longValue();
	}

	public static void setDoneCode(long doneCode) {
		s_doneCode.set(new Long(doneCode));
	}
	public static void clearDoneCode() {
		s_doneCode.remove();
		ServiceManager.setDoneCode(null);
	}

 JDK源码:

ThreadLocal类:
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }

 

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

 

    /**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param  t the current thread
     * @return the map
     */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值