Web应用程序Java中的线程

时间:2012-12-26 15:26:42

标签: java tomcat web-applications

好吧,我试图在Java中构建一个Web应用程序,每次有人在地址中发出http请求时启动一个线程。 这是一个很好的实践?可以工作?优缺点?下面的工作是使用弹簧示例,只是添加了我想要的线程

ps:这是在tomcat中运行的

> HomeController.java

    @Controller  public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);

        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

        String formattedDate = dateFormat.format(date);

        model.addAttribute("serverTime", formattedDate );
        new Teste().start();
        return "home";
    }}class Teste extends Thread{

    @Override
    public void run() {

        while(true){
            System.out.println("im in thread");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
    }

> web.xml

    <?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.5"xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/n/javaee/web-app_2_5.xsd">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

> servlet-context.xml

    <?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.example.threadTestes" />



</beans:beans>

2 个答案:

答案 0 :(得分:2)

在托管环境中进行线程通常是个坏主意。为什么不在每次有人发送请求时使用像JMS这样的抽象来启动后台处理程序?这样你可以控制活动线程的数量(jms池大小)

答案 1 :(得分:1)

为每个请求启动一个线程在任何应用程序中都是一个糟糕的想法,无论是托管的还是非托管的,并且#1的原因是操作系统可以用来为新线程分配堆栈的内存量是有限的;并且它不仅有限,它在盒子上的所有进程之间共享(尽管你的java进程可能只允许使用其中的一部分)。现在假设这些线程根本不会终止,或者在新请求不断进入时不会足够快地终止 - 操作系统最终将耗尽新线程的空间;取决于操作系统及其设置,结果可能会因新的Thread()中相当迷人的OutOfMemoryError而变得明显无响应,因为您的java进程占用了所有可用空间,并且根本无法创建新线程。所以:1)处理请求至少使用线程池(Executor);如果你需要持久性,JMS是一个选项,但是你再次处理池中的请求 - 它只是从JMS 2提供的)用于某种维护任务,你可以在app启动期间启动一个单独的线程。在这两种情况下都要自行清理并在关机期间停止其他线程。