转载自:https://blog.csdn.net/doctor_who2004/article/details/115647638
下面是个人理解结论:
场景:页面http调用,一次调用,底层同时调用多个服务,部分结果可丢失情形。
实现:
担心调用量太多,允许丢弃部分结果,并行执行,定义线程池。自定义RejectedExecutionHandler,取消执行( ((FutureTask) r).cancel(true)),这样应该是最合适的。以防万一,future外面还可以再加个超时时间。
executor.setQueueCapacity(0); executor.setRejectedExecutionHandler(new MyDiscardPolicy ());
web调用时Executor.submit(),如果设置AbortPolicy时没有返回结果,只会抛出异常。这种情况可以自定义DiscardPolicy。
public static class MyDiscardPolicy implements RejectedExecutionHandler { /** * Creates a {@code DiscardPolicy}. */ public Erp20DiscardPolicy() { } /** * Does nothing, which has the effect of discarding task r. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { loggerUtil.info(LogData.builder().data(" Erp20AbortPolicy Task " + r.toString() +" rejected from " + e.toString())); ((FutureTask) r).cancel(true);//这种会抛异常,future.get()时需要try catch } }
for (Future<Map> future : futureList) { try { Map tempMap = future.get(); }catch (Exception e){ // logger.error(); } }