feat: 开发线程池拒绝策略及 SPI 方式集成.

pull/161/head
chen.ma 3 years ago
parent 1e1f821e46
commit 56e57c39a2

@ -0,0 +1,34 @@
package io.dynamic.threadpool.starter.spi.rejected;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.concurrent.RejectedExecutionHandler;
/**
*
*
* @author chen.ma
* @date 2021/7/10 23:51
*/
public interface CustomRejectedExecutionHandler {
/**
*
*
* @return
*/
RejectedExecutionHandlerWrap generateRejected();
@Getter
@Setter
@AllArgsConstructor
class RejectedExecutionHandlerWrap {
private Integer type;
private RejectedExecutionHandler rejectedExecutionHandler;
}
}

@ -0,0 +1,86 @@
package io.dynamic.threadpool.starter.toolkit.thread;
import io.dynamic.threadpool.starter.spi.DynamicTpServiceLoader;
import io.dynamic.threadpool.starter.spi.rejected.CustomRejectedExecutionHandler;
import java.util.*;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Stream;
/**
*
*
* @author chen.ma
* @date 2021/7/10 23:16
*/
public enum RejectedTypeEnum {
/**
* 线
*/
CALLER_RUNS_POLICY(1, new ThreadPoolExecutor.CallerRunsPolicy()),
/**
* ,
*/
ABORT_POLICY(2, new ThreadPoolExecutor.AbortPolicy()),
/**
* ,
*/
DISCARD_POLICY(3, new ThreadPoolExecutor.DiscardPolicy()),
/**
* , ,
*/
DISCARD_OLDEST_POLICY(4, new ThreadPoolExecutor.DiscardOldestPolicy()),
/**
* ,
*/
RUNS_OLDEST_TASK_POLICY(5, RejectedPolicies.runsOldestTaskPolicy()),
/**
* 使,
*/
SYNC_PUT_QUEUE_POLICY(6, RejectedPolicies.syncPutQueuePolicy());
/**
*
*/
public Integer type;
/**
* 线
*/
public RejectedExecutionHandler rejectedHandler;
RejectedTypeEnum(Integer type, RejectedExecutionHandler rejectedHandler) {
this.type = type;
this.rejectedHandler = rejectedHandler;
}
public static RejectedExecutionHandler createPolicy(Integer type) {
Optional<RejectedExecutionHandler> rejectedTypeEnum = Stream.of(RejectedTypeEnum.values())
.filter(each -> Objects.equals(type, each.type))
.map(each -> each.rejectedHandler)
.findFirst();
// 使用 SPI 匹配拒绝策略
RejectedExecutionHandler resultRejected = rejectedTypeEnum.orElseGet(() -> {
Collection<CustomRejectedExecutionHandler> customRejectedExecutionHandlers = DynamicTpServiceLoader
.getSingletonServiceInstances(CustomRejectedExecutionHandler.class);
Optional<RejectedExecutionHandler> customRejected = customRejectedExecutionHandlers.stream()
.map(each -> each.generateRejected())
.filter(each -> Objects.equals(type, each.getType()))
.map(each -> each.getRejectedExecutionHandler())
.findFirst();
return customRejected.orElse(ABORT_POLICY.rejectedHandler);
});
return resultRejected;
}
}
Loading…
Cancel
Save