当我的请求出现在我的控制器上时,executorService创建一个线程池并创建一些线程来执行某些逻辑,我的请求返回到浏览器。我的问题从这里开始,在服务器端运行的线程需要会话对象,线程将会话作为空。在响应返回到客户端后,我用什么方法来设置会话值。下面是代码,请给出一些合适的解决方案,这样我就可以在请求完成后得到会话值。
@RequestMapping(value =“/ expandAllController”,method = RequestMethod.POST) public @ResponseBody void expandAllController(@RequestParam final String [] controllerList,final HttpServletRequest request){
int listSize=controllerList.length;
BlockingQueue controllerDataQueue=cacheUtility.initBlockingQueue(listSize);
ExecutorService executor=Executors.newCachedThreadPool();
for(String controllerID:controllerList){
executor.submit(new producer(controllerID,request,controllerDataQueue));
}
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// data fetching Thread
}
private class producer implements Runnable{
Object responseObj=null;
String controllerID;
HttpServletRequest request;
BlockingQueue controllerDataQueue;
producer(String controllerID ,HttpServletRequest request, BlockingQueue controllerDataQueue ){
this.controllerDataQueue=controllerDataQueue;
this.controllerID=controllerID;
this.request=request;
}
@Override
public void run() {
int ThreadCount=0;
final HttpSession session = request.getSession();
final CommonSettings commonSettings = CommonSettings
.getInstance(session);
// for(String controllerID:controllerList){
controllerData.setControllerId(controllerID);
responseObj=expandController(controllerData,session);
if(responseObj!=null){
try {
controllerDataQueue.put(responseObj);
ThreadCount++;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
答案 0 :(得分:0)
直接从控制器方法在会话中存储空容器(例如,同步集或列表),然后将此容器传递给每个任务,并使任务将其响应添加到容器中。
另外,请考虑重用始终相同的线程池。浪费资源总是开始一个新的。如果有太多的请求进入,你将有太多的并行运行的线程,这正是线程池用来避免的。