セルフライトスレッドプール

1761 ワード

@Data
@AllArgsConstructor
public class ReleaseTask {

    /**
     *          sessionID
     */
    private String sessionId;
    /**
     *            
     */
    private String massage;
    /**
     *    runable  
     */
    private Runnable runnable;

}
@Slf4j
@Service
public class RtpService {

    /**
     *      
     */
    private static final int CORE_POOL_SIZE = 2;
    /**
     *      
     */
    private static final int MAXIMUM_POOL_SIZE = 10;
    /**
     *         
     */
    private static final long KEEP_ALIVE_TIME = 1;

    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private WebSocketServer webSocketServer;

    @SuppressWarnings("unchecked")
    RtpService() {
        threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.MINUTES,
                new ArrayBlockingQueue(10), new DefaultThreadFactory("Release Thread Pool"));
    }

    /**
     *     
     * @param task    Runnable  
     * @return  true     ,false     
     */
    public boolean execute(ReleaseTask task) {

        Runnable run = () -> {
            // 1.     
            // 2.   
            try {
                task.getRunnable().run();
                webSocketServer.sendMessageThe(task.getSessionId(),task.getMassage()+"  ");
            } catch (Exception e) {
                webSocketServer.sendMessageThe(task.getSessionId(),task.getMassage()+"  ");
            }
            // 3.    
        };

        try {
            threadPoolExecutor.execute(run);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }