Fork me on GitHub

【01-14】java ThreadLocal工具类

自定义ThreadLocal

package concurrent;

import java.util.HashMap;
import java.util.Map;

/**
 * @author aloha_world_
 * @date 2016年9月13日 下午11:40:52
 * @version v1.00
 * @description 继承自ThreadLocal类并实现其init方法
 */
public class MyThreadLocal extends ThreadLocal<Map<String, Object>> {

	private Map<String, Object> innerMap;

	@Override
	protected Map<String, Object> initialValue() {
		innerMap = new HashMap<String, Object>();
		return innerMap;
	}

	public Object get(String key) {
		return innerMap.get(key);
	}

	public void reset() {
		innerMap.clear();
	}

	public void set(String key, Object value) {
		innerMap.put(key, value);
	}

	@Override
	public void remove() {
		super.remove();
	}

}

操作ThreadLocal的工具类

package concurrent;

/**
 * @author aloha_world_
 * @date 2016年10月17日 下午10:30:23
 * @version v1.00
 * @description 操作ThreadLocal的工具类
 */
public class ThreadContextHolder {
	public static MyThreadLocal threadLocal = new MyThreadLocal();

	public static void reset() {
		threadLocal.reset();
	}

	public static void put(String key, Object value) {
		threadLocal.get().put(key, value);
	}

	public static void remove(String key) {
		threadLocal.get().remove(key);
	}
}


更一般的工具类

package org.alohaworld.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author aloha_world_
 * @date 2016年11月7日 下午11:37:05
 * @version v1.00
 * @description
 */
public class ThreadContextHolder {
	private static final Log logger = LogFactory.getLog(ThreadContextHolder.class);

	public static final ThreadLocal<Map<String, Object>> context = new MyThreadLocal();

	private static class MyThreadLocal extends ThreadLocal<Map<String, Object>> {
		@Override
		protected Map<String, Object> initialValue() {
			return new HashMap<String, Object>();
		}
	}

	public static Object get(String key) {
		return getMap().get(key);
	}

	private static Map<String, Object> getMap() {
		return context.get();
	}

	public static void put(String k, Object v) {
		logger.info("key:" + k + " value:" + Thread.currentThread().getName() + " added to threadlocal");
		getMap().put(k, v);
	}

	public static void reset() {
		getMap().clear();
	}
}

posted @ 2017-01-14 23:35  aloha_world  阅读(777)  评论(0编辑  收藏  举报