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,
*
------