Search code examples
javamultithreadingjdbctemplatejava.util.concurrent

Java Executor not working on JdbcTemplate


I am trying to execute a query with a jdbcTemplate using an executor object but for some reason the program doesn't go inside the jdbcTemplate.

        ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_CONCURRENT_THREADS);
        executor.execute(new Runnable() {
        @Override
        public void run() {
            inboundJdbcTemplate.query(selectQuery, new RowCallbackHandler() {
                @Override
                public void processRow(ResultSet rs) throws SQLException {//<-instruction pointer never goes to this line
                    try {
                        //buffer.put(buildDataPoint(rs, testPermutationId));
                        System.out.println(rs.getString(0));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    }
                }
            });
            try {
                buffer.put(STOPPING_TOKEN);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

Can anyone help me with this stupid bug?


Solution

  • I found a solution to the problem.

    I needed a CompletionService in order to make sure that I know when the execution of the JdbcTemplate finishes.

    {...
     ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_CONCURRENT_THREADS);
     CompletionService<String> completionService = new ExecutorCompletionService (executor);
    
     completionService.submit(new Runnable() {
        @Override
        public void run() {
            inboundJdbcTemplate.query(selectQuery, new RowCallbackHandler() {
                @Override
                public void processRow(ResultSet rs) throws SQLException {
                    try {
                        buffer.put(buildDP(rs, Id));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
     }, "Success");
    
     try{
          Future<String> take1 = completionService.take();
          String s = take1.get();
          if(!"Success".equals(s)) throw new RuntimeException("Error Occured");
     catch (InterruptedException | ExecutionException e) {
            LOG.error(" Could not execute DataExtraction",e);}
     executor.shutdown();
    ...}