Open new thread in Tomcat

喜夏-厌秋 提交于 2019-12-23 20:14:19

问题


I'm just asking theoretical question.

I' have an operation which takes some period of time which is performed in some Servlet doGet/doPost method or inside of Spring MVC controller . is is good idea to open new background thread an perform it there? Won't it cause performance issue?

Would I get some befits if I were using jBoss JMS system in this case?


回答1:


It's OK (Tomcat is not a JavaEE container). Since you mention Spring MVC, I will suggest using @Async on the method you want to execute - the new thread will be spawned by spring (which is very much the same as the equivalent JavaEE annotation)




回答2:


Servlet 3.0 introduced async processing, which would help here.

Basically, you mark the servlet as supporting async processing, then using the context to start a new thread - the container does it for you so that you don't need to handle anything with threads yourself.

See this blog article for an idea. The advantage of doing this, is that your servlet will be portable to full Java EE containers which won't let you start your own threads.

Otherwise, consider using the ExecutionService and friends from java.util.concurrent. There is no real reason to use "new Thread()" yourself these days.




回答3:


Well, since Tomcat is not a Java EE container, but just a Servlet Container, you can open new threads without any problem (apart from the tipical issues of multithreading you should deal with ;).

JMS is a solution to decouple modules full blown middleware (a whole new run-time) that takes care of messages. This approach could be too complex for you if you just want to decouple a single process for efficiency reasons.

If you are using Spring 3.0, i would suggest you to use asynchronous calls. You just annotate a method of a bean with @Async, and you are done :).



来源:https://stackoverflow.com/questions/6640418/open-new-thread-in-tomcat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!