我应该在Spring Component中使用ExecutorService吗?

时间:2018-11-21 06:13:01

标签: spring spring-boot executorservice

我有一个看起来像这样的弹簧组件:

@Component
public class ProfileService {

  private final ExecutorService executorService = ExecutorFactory.newThreadPoolExecutor(getClass().getSimpleName(),
  5, 100, 10, TimeUnit.MINUTES,
  new ArrayBlockingQueue<>(1), new ThreadPoolExecutor.AbortPolicy());

  public Map<Integer, String> getProfiles(String client, Set<String> pIds) {
    Map<String, Future<Optional<Profile>>> profileFutures = new HashMap<>(pIds.size());
    for (String pId : pIds) {
      locationsFutures.put(clusterMcId, executorService.submit(() -> getProfile(client, pId)));
    }
    Map<String, String> profileNames = new HashMap<>();
    for (String pId : profileFutures.keySet()) {
        profileFutures.get(pId).get(200, TimeUnit.MILLISECONDS).ifPresent(
          profile -> profileNames.put(pId, profile.getName());
    }
    return profileNames;
  }

我只是并行调用以使用其ID获取个人资料,并等待期货交易完成。向RejectedExecutionException提交任务时,我不断收到executorService。现在我的问题如下:

  1. 在弹簧组件中使用ExecutorService是个好主意吗?由于将在并行的tomcat请求中使用相同的组件,并且每个请求向线程池提交5个任务,因此它不会有5个并发请求任务吗?
  2. 有没有更好的方法来做我的工作?我可以增加阻塞队列的大小,但是可以保留多长时间。 (不可选择分批)。

0 个答案:

没有答案