public class EditProcessor { private final ContextCopyThreadPoolExecutor executor = new ContextCopyThreadPoolExecutor(); public EditProcessor() { executor.initialize(); executor.setCorePoolSize(4); executor.setMaxPoolSize(4); } public void demo() { //计数器 CountDownLatch countDownLatch = ThreadUtil.newCountDownLatch(details.size()); //异常收集 AtomicBoolean isException = new AtomicBoolean(false); AtomicReference<Exception> atomicException = new AtomicReference<>(); details.forEach(detail -> executor.execute(() -> { try { if (isException.get()) { return; } /* 业务功能 */ } catch (Exception e) { isException.set(true); atomicException.set(e); e.printStackTrace(); } finally { countDownLatch.countDown(); } })); countDownLatch.await(); if (isException.get()) { throw atomicException.get(); } } }
public class ContextCopyThreadPoolExecutor extends ThreadPoolTaskExecutor { /** * */ private static final long serialVersionUID = -1392123770572111202L; public ContextCopyThreadPoolExecutor() { setTaskDecorator(new ContextCopyDecorator()); } }
public class ContextCopyDecorator implements TaskDecorator { /** * * @see org.springframework.core.task.TaskDecorator#decorate(java.lang.Runnable) */ @Override public Runnable decorate(Runnable runnable) { final RequestAttributes context = RequestContextHolder.currentRequestAttributes(); final SecurityContext securityContext = SecurityContextHolder.getContext(); return () -> { try { RequestContextHolder.setRequestAttributes(context); SecurityContextHolder.setContext(securityContext); runnable.run(); } finally { SecurityContextHolder.clearContext(); RequestContextHolder.resetRequestAttributes(); } }; } }