Create a timeout for a set of tasks assigned to a threadpool java

Viewed 3733

Hi I am having a problem regarding timing out tasks assigned to a thread pool java.

In detail:

  1. I have implemented an API which runs some queries in parallel and returns the response.
  2. There is a fixed thread pool created via Executors.newFixedThreadPool(40). Whenever someone calls this API, a set of 10 tasks are schedules on this thread pool. These tasks internally execute a set of queries on Mysql.
  3. I have to return the response for the API with an SLA of 6-7 sec. So I have to create a timeout for all the 10 tasks that were scheduled on the thread pool. I know how to timeout a single task (It throws an interrupted exception although the thread becomes free only if it is completed once it is started).
  4. I also don't want to overload the thread pool. So I have created a timeout of 60 sec for all the queries that run via the tasks assigned to this thread pool. So the threads become free to take up another task within a minute.

Question:

Is there an elegant way to solve this problem?

@Component
public class MyHandler {
    @PostConstruct
    public void init() {

        /*
        * Naming thread pool to identify threads in the thread dump
        * */

        ThreadFactory threadFactory = new ThreadFactoryBuilder()
            .setNameFormat("my-thread-%d").build();

        executorService = Executors.newFixedThreadPool("40", threadFactory);
    }

    @PreDestroy
    public void destroy() {
        executorService.shutdown();
    }

    public void update() {
        List<Future<Boolean>> results = new ArrayList<>();
        results.add(executorService.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                executeQuery();
                return true;
            }
        }));

        /*
        * 9 more such tasks
        */


         for (Future<Boolean> result : results) {
            try {
                result.get();
            } catch (InterruptedException | ExecutionException e) {
                LOGGER.error("Failed with unknown error", e);
            }
        }
    }
}

executeQuery() has a timeout scheduled for 60 sec.

2 Answers
Related