!46 双重校验锁实现单例需加上volatile禁止指令重排

Merge pull request !46 from CodeNose/fixbug_20211026_DCLBug
This commit is contained in:
chopper711 2021-10-27 02:42:29 +00:00 committed by Gitee
commit ab0b7f1591

View File

@ -24,7 +24,10 @@ public class ThreadPoolUtil {
*/ */
private static final BlockingQueue<Runnable> BQUEUE = new ArrayBlockingQueue<Runnable>(100); private static final BlockingQueue<Runnable> BQUEUE = new ArrayBlockingQueue<Runnable>(100);
private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, ALIVE_TIME, TimeUnit.MILLISECONDS, BQUEUE, new ThreadPoolExecutor.CallerRunsPolicy()); private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, ALIVE_TIME, TimeUnit.MILLISECONDS, BQUEUE, new ThreadPoolExecutor.CallerRunsPolicy());
public static ThreadPoolExecutor threadPool; /**
* volatile禁止指令重排
*/
public static volatile ThreadPoolExecutor threadPool;
static { static {
POOL.prestartAllCoreThreads(); POOL.prestartAllCoreThreads();
@ -49,22 +52,20 @@ public class ThreadPoolUtil {
} }
/** /**
* dcs获取线程池 * DCL获取线程池
* *
* @return 线程池对象 * @return 线程池对象
*/ */
public static ThreadPoolExecutor getThreadPool() { public static ThreadPoolExecutor getThreadPool() {
if (threadPool != null) { if (threadPool != null) {
return threadPool; return threadPool;
} else { }
synchronized (ThreadPoolUtil.class) { synchronized (ThreadPoolUtil.class) {
if (threadPool == null) { if (threadPool == null) {
threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool(); threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
return threadPool;
}
return threadPool;
} }
} }
return threadPool;
} }
public static ThreadPoolExecutor getPool() { public static ThreadPoolExecutor getPool() {