Reputation: 1651
So in the following code, when I do yService.performAction()
it does it for many items and is taking too much time.
I have been advised to try to use threads to make this faster so I went online and looked and found that it's not advisable to spawn new child threads from the controller as it might mess up the Java EE container thread pool. If my yService.performAction(
) is taking time to run and need to make it fast, what options do I have?
Many people have been suggesting to use Quartz to spawn new threads. I am not sure if I want to do something that complex. How can I run that specific service in separate threads? Is there any simple way to do it?
@Controller
@RequestMapping("/test")
public class TestController {
private static final Logger logger = Logger.getLogger(TestController.class);
@Autowired
XService xService;
@Autowired
private YService yService;
@RequestMapping(method = { RequestMethod.GET })
public void testCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
List<SL> somelist = XService.getAllX();
StringBuffer status = new StringBuffer("SUCCESS\n\n");
for (SL sl : somelist) {
boolean flag = false;
try {
flag = yService.performAction(sl);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write(status.toString());
} catch (Exception e) {
logger.error(e.getMessage(), e);
response.getWriter().write("FAILED");
}
}
}
Upvotes: 1
Views: 948
Reputation: 59586
Your best option is to use an ExecutorService and call invokeAll(). You can retrieve an instance by calling Executors.newFixedThreadPool().
Upvotes: 1