Thursday, 10 January 2013

Thread safe variables

Servlets : Multithreaded model by default :


There is no such interface as MultiThreadedModel. Servlets are intrinsically multithreaded. This means a single instance can be accessed by more than one thread. 

If the container receives multiple requests for one servlet simultaneously, the service () method of that servlet will be executed concurrently in multiple threads

If a servlet implements the SingleThreadModel interface, the container will not execute the service () method in more than one thread simultaneously.
The servlet container may synchronize access to a single instance of the servlet. 
However, servicing requests sequentially seriously hurts performance. To avoid the performance problem, a servlet container may create multiple instances of the servlet class.



Different variables in both models thread safe or not:-
1. Single Thread Model:- 
Local variables:- are defined within the body of a method. [Levi] Always thread-safe.

Instance variables:- Instance variables are defined within the class body and are separately assigned to each instantiated object. Thread-safe only for SingleThreadModel 

Class or static variables:- Only one copy of a class variable exists across all the instances of the object belonging to the class for which it is declared.
Class variables , or static variables, are shared among all instances of a servlet. NEVER thread-safe 
(No, not even if servlet implements SingleThreadModel.) 

Request attributes :- Always thread-safe 
Session attributes:- NEVER thread-safe 
Context attributes :- NEVER thread-safe 

No comments:

Post a Comment