001/*
002 *  Copyright (c) 2023-2026, Agents-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package com.agentsflex.core.util;
017
018import java.util.concurrent.*;
019
020/**
021 * @author michael yang (fuhai999@gmail.com)
022 */
023public class NamedThreadPools {
024
025    public static ExecutorService newFixedThreadPool(String prefix) {
026        int nThreads = Runtime.getRuntime().availableProcessors();
027        return newFixedThreadPool(nThreads, prefix);
028    }
029
030
031    public static ExecutorService newFixedThreadPool(int nThreads, String name) {
032        return new ThreadPoolExecutor(nThreads, nThreads,
033            0L, TimeUnit.MILLISECONDS,
034            new LinkedBlockingQueue<>(nThreads * 2),
035            new NamedThreadFactory(name));
036    }
037
038
039    public static ExecutorService newCachedThreadPool(String name) {
040        return newCachedThreadPool(new NamedThreadFactory(name));
041    }
042
043
044    public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
045        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
046            60L, TimeUnit.SECONDS,
047            new SynchronousQueue<Runnable>(),
048            threadFactory);
049    }
050
051
052    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String name) {
053        return newScheduledThreadPool(corePoolSize, new NamedThreadFactory(name));
054    }
055
056
057    public static ScheduledExecutorService newScheduledThreadPool(
058        int corePoolSize, ThreadFactory threadFactory) {
059        return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
060    }
061}