keepmoving
keepmoving

Reputation: 2043

How to handle ThreadPool/ExecutorService in Spring

I want to handle multi Thread in spring mvn model. I have written this code

@RequestMapping("/indialCall")
    @ResponseBody
    public String indialCall(HttpServletRequest request) {
    String result = "FAIL";
    try {
        Map<String, String> paramList = commonUtilities.getParamList(request);
        logger.info("indialCall paramList :::" + paramList);
//      System.out.println("indial-call paramList :::" + paramList);
        result = inDialHandler.processIndialWork(paramList);
        logger.info(result);
    } catch (Exception e) {
        logger.info("Error :" + e);
    }

    return result;
    }




public String processIndialWork(final Map<String, String> paramList) {

                final Boolean sendSms = Boolean.parseBoolean(paramList.get(constantService.getSendSms()));
                //assume it is always true
                if(true){
                        Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String sessionId = (String) paramList.get(constantService.getInDialSession());
                            String msisdn = (String) paramList.get(constantService.getInDialMsisdn());
                            //This method will save the entry into database
                            saveMissedCall(callStartDate, sessionId, msisdn, vmnNo, advId, enterpriseId, sendSms, advertiser);
                        }
                    });
                    thread.start();
                    return "1";
                }
                }

In this code i am using thread creation on every http request. Which is not good for my case. because system get 50 request /sec. and when i see the cpu usage it is too high.

            I am calling this thread for async communication so that calling party can get response instantly
            and later on application do the further processing.

            I want to use the Executor service but do not know how to do this. Can some one guide me or can write 
            few line of code for me to implment the correct thread pool executor. 

Upvotes: 1

Views: 6719

Answers (1)

Panther
Panther

Reputation: 3339

First define a simple taskExecutor in your config file.

  <bean id="taskExecutor"
    class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="maxPoolSize" value="10" />
    <property name="WaitForTasksToCompleteOnShutdown" value="true" />
</bean>

Create spring bean with prototype scope (prototype is important as you want to give each thread different data), and they will run simultaneously.

This spring bean will implement runnable with run method and will have class level variable paramlist for getting vales.

 public class MyRunnableBean implements runnable{
   private Map<String, String> paramList();
// add setter
 public void run(){
        // your logic



 }


}

Inject task executor (singleton) in your existin bean , get the instances of this runnable bean in your existing bean set the paramlist and add it in executor :-

   MyRunnableBEan myRunnableBEan = applicationContext.getBean("myRunnable");
   myRunnableBean.setParamList(/* your paramlist*/ );
   taskExecutor.execute(myRunnableBean);

Correct the compilation and syntax error, this sample code written on notepad, i don't have java on my machine.

Upvotes: 3

Related Questions