package com.qiwu.inference.common.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** *
 * ThreadLocal을 사용하여 스레드 간 객체를 전파하기 위한 유틸리리 클래스
 * 
*/ public class ThreadLocalUtil { private static final Logger LOGGER = LoggerFactory.getLogger(ThreadLocalUtil.class); // 스레드 간 공유 객체를 저장하기 위한 ThreadLocal private static ThreadLocal> threadLocal = new ThreadLocal>(); /** *
     * ThreadLocal 用于在线程之间传播对象的实用程序类
     * 
* @return */ private static Map getThreadLocal() { if (threadLocal.get() == null) { Map sharedObject = new HashMap(); threadLocal.set(sharedObject); } return threadLocal.get(); }//end of getThreadLocal() /** *
     * 以在线程间共享对象中指定的键的名称存储对象
     * 
* @param key * @param object */ public static void add(String key, Object object) { // NOPMD getThreadLocal().put(key, object); }//end of add() /** *
     * 从线程之间的共享对象导入与指定键相对应的对象
     * 
* @param key * @return */ public static Object get(String key) { // NOPMD return getThreadLocal().get(key); }//end of get() /** *
     * 调查是否存在与线程间共享对象上指定的键相对应的对象
     * 
* @param key * @return */ public static boolean isExist(String key) { Object object = getThreadLocal().get(key); if (object != null) { return true; } else { return false; } }//end of isExist() /** *
     * 初始化线程之间的共享对象
     * 
*/ public static void clearSharedObject() { getThreadLocal().clear(); threadLocal.set(null); }//end of clearSharedObject() /** *
     * 
* @return */ public static String[] getThreadLocalKeys() { String[] arrKeys = new String[getThreadLocal().size()]; Iterator keyIter = getThreadLocal().keySet().iterator(); int i = 0; while (keyIter.hasNext()) { arrKeys[i] = keyIter.next(); i++; } return arrKeys; }//end of getThreadLocalKeys() /** *
     * 
* @return */ public static int size() { return getThreadLocal().size(); }//end of size() /** *
     * 
* @return */ public static Object[] getThreadLocalValues() { int size = size(); String[] arrKeys = getThreadLocalKeys(); Object[] values = new Object[size]; for (int i = 0; i < size; i++) { values[i] = getThreadLocal().get(arrKeys[i]); } return values; }//end of getThreadLocalValues() /** *
     * 
*/ public static void toPrintString() { int size = size(); StringBuffer str = new StringBuffer(); String[] keys = getThreadLocalKeys(); Object[] values = getThreadLocalValues(); for (int i = 0; i < size; i++) { str.append(" " + keys[i] + " = " + values[i] + " \n"); } LOGGER.info("{}", str.toString()); }//end of toPringString() }// end of ThreadLocalUtil.java