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,

 

------


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值