zoukankan      html  css  js  c++  java
  • Servlet Only One Instance In Container?

    the answer is depend on.

    You can let the servlet implement SingleThreadModel to get the container to create a pool of multiple instances of the same servlet class. The maximum pool size depends on the container used, on Tomcat for example, this is 20. But, a big but, this interface is deprecated since Servlet 2.4! We should actually be writing servlets in a thread-safe manner, without assigning request- and/or session scoped data as an instance variable of the servlet. This way it's safe to use a single servlet instance across multiple threads (read: across multiple HTTP requests).

    Servlet container instantiates single instance for each servlet declaration. That means, that you can have multiple servlet instances, but you need to declare the servlet as many times as many instances you want/need. This also brings the question of how servlets would be invoked ... they would need to be mapped to different paths.

    Another way you can do this is to make a pool of handlers which your single servlet may call.

    how to make them thread-safe: that depends on what exactly you want to do in those handlers. It's hard to tell you in general.

    If you're asking about thread-safe pool, you can use Apache Commons Pool library, or some BlockingQueue (e.g. LinkedBlockingQueue) in Java: queue may contain your handlers. Servlet willtake() first handler, use it, and put() it back after it's done. (This is just an example of course, there are many ways to implement pool).

    But ... make sure you really need design like this, maybe your requirements can be satisfied by something simpler? (If your goal is to limit number of concurrent requests handled at the same time, maybe it's enough to just limit number of HTTP worker threads in your container? Or if that's not enough, you can use a limiting filter?)

    Further Read:

    Related:

    see also 

    java servlet instantiation and session variables

    conclusion:

    Only one instance if you do not implement singlethreadmodel.but, this interface is deprecated since Servlet 2.4!

  • 相关阅读:
    Django models中的null和blank的区别
    微服务
    幂等性
    restful规范
    related_name
    数据库 引擎,数据类型,约束
    数据库 基本操作
    python 常见算法
    python if,循环的练习
    python数据类型、if判断语句
  • 原文地址:https://www.cnblogs.com/malaikuangren/p/2593926.html
Copyright © 2011-2022 走看看