`

servlet - thread safe

 
阅读更多

 

servlet - thread safe

 

------

servlet's thread mode

 

by default, each servlet has only one instance,

each request will have it's own thread to access the single servlet instance,

 

the thread safe is related to JVM memory mode,

 

fields & thread safe:

* static fields

for static fields of servlet, has only one copy, might be accessed by multi thread concurrently, so there might be thread unsafe,

* non-static fields

for non-static fields of servlet,

* local variable of non-static method

for local variable of non-static method,each thread has it's own copy of the local variable, so it's totally thread safe,

 

------

possible thread unsafe

 

* static fields of servlet

all thread access the same variable, so it's thread unsafe,

* non-static fields

usually, it's safe, 

but according to JVM memory mode, in some special case(e.g. thread sleep), the memory might not be synchronized, thus there might be thread unsafe,

 

------

ways to make thread safe

 

* take case of your program

servlet is born to be thread safe, so if you wirte good program you will be safe,

* use synchronized keyword

use synchronized on fields/method/code_block, so that only one thread could access concurrently,

drawback: of course this will reduce efficiency more or less, but it provide thread safe,

* use local variable

local variable of method is totally thread safe,

* implement SingleThreadModel interface (deprecated)

since servlet2.4 this interface is deprecated, so don't use this in most case,

servlet that implement SingleThreadModel, will create a new servlet instance for each request,

so this is totally safe, but low efficiency and expensive,

 

------


分享到:
评论

相关推荐

    Java_for_the_Web_with_Servlets

    - **Thread-Safe Servlets**: Servlets must be thread-safe to handle concurrent requests efficiently. Techniques for creating thread-safe servlets are discussed in the book. ##### Writing Servlet ...

    freebsd安装软件

    配置MySQL安装目录和数据存放目录:`./configure --localstatedir=/usr/local/mysql/var --prefix=/usr/local/mysql --enable-assembler --with-extra-charsets=complex --enable-thread-safe-client --with-big-...

    Struts、Spring、Hibernate三大框架的原理和优点.docx

    然而,其缺点是Action的安全性问题(thread-safe),Taglib的学习曲线较陡,以及Controller的拆分增加了系统复杂性。 Spring是一个全面的后端应用框架,其核心是IoC(Inversion of Control,控制反转)和AOP...

    [新闻文章]NTsky新闻发布(提供JavaBean)v1.0_ntskynewsv1.0javabean.rar

    - JavaBean遵循一些基本的规则,比如它是公共的(public)、无状态的(stateful)且线程安全的(thread-safe)。 - 它通常有一个默认的构造器,允许无参数初始化。 - 它包含getter和setter方法来访问和修改属性。...

    Struts,Spring,Hibernate优缺点

    2. Struts 的 Action 必需是 thread-safe 方式,它仅仅允许一个实例去处理所有的请求。 3. 测试不方便。Struts 的每个 Action 都同 Web 层耦合在一起,这样它的测试依赖于 Web 容器,单元测试也很难实现。 4. 类型...

    亚信面试题目

    * Vector 的方法都是同步的(Synchronized),是线程安全的(thread-safe),而 ArrayList 的方法不是。 * Vector 和 ArrayList 都可以将容量扩大,但是 Vector 会将容量翻倍,而 ArrayList 只增加 50% 的大小。 2....

Global site tag (gtag.js) - Google Analytics