/**
 * $Id$
 * Copyright(C) 2015-2020 kowlone - internet center, All Rights Reserved.
 */
package com.liquidnet.commons.lang.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

/**
 * @author <a href="kowlone2006@163.com">kowlone</a>
 * @version 1.0 2015年09月23日 17:50:00
 */
public class ThreadLocalPool {

	private static final List<ThreadLocal> lstLocal = new ArrayList<>();

	/**
	 * 创建全局管理的ThreadLcocal,只有类的静态变量中调用才有效
	 *
	 * @param <T>
	 *
	 * @return
	 */
	public static <T> ThreadLocal<T> createThreadLocal(Supplier<? extends T> supplier) {
		ThreadLocal<T> local = supplier == null ? new ThreadLocal<>() : ThreadLocal.withInitial(supplier);
		lstLocal.add(local);
		return local;
	}

	public static <T> ThreadLocal<T> createThreadLocal() {
		return createThreadLocal(null);
	}

	/**
	 * 当前线程所有业务处理结束后,需要调用此方法,清除所有ThreadLocal缓存
	 */
	public static void clear() {
		lstLocal.forEach(t -> t.remove());
	}

	private static ExecutorService exec = Executors.newFixedThreadPool(5);
	private static final ThreadLocal<String> threadLocal = ThreadLocalPool.createThreadLocal();

	public static void main(String[] args) {

		for (int i = 0; i < 10; i++) {
			final int k = i;
			exec.execute(() -> {
				threadLocal.set("哈哈哈" + k);
				//				ThreadLocalPool.clear();
				System.out.println("期待输出: " + k + "  实际输出:" + threadLocal.get());

			});
		}

		exec.shutdown();
	}
}
