SlideShare una empresa de Scribd logo
1 de 28
1
Thread-Safe Servlets
Helmi ben abdallah @rchitect JEE
2
THE FOLLOWING SUN CERTIFIED WEB COMPONENT DEVELOPER
FOR J2EE PLATFORM EXAM OBJECTIVES COVERED IN THIS
CHAPTER:
7.1 Identify which attribute scopes are thread-safe:
Local variables
Instance variables
Class variables
Request attributes
Session attributes
Context attributes
7.2 Identify correct statements about differences between the
multithreaded and single-threaded servlet models.
7.3 Identify the interface used to declare that a servlet must use the
single thread model.
3
• Threads seem to be a topic that most developers wish to
avoid but can’t.
• In a single-threaded environment, ensuring the integrity
of a Java class is as easy as making all instance variables
private and providing public accessor or mutator methods.
• In a multithreaded environment, achieving a “thread-
safe” application is a bit more complex.
• Servlets are intrinsically multithreaded : a single
instance can be accessed by more than one thread.
Because servlets, by their nature, are designed for
multiple users, creating a thread-safe environment is a
vital key to the success of the application
4
Attributes
• Local variables : Short-term values that are often used as loop
iterators.
• Instance variables : Data that persists for the life of the servlet,
shared by all concurrent users.
• Class variables :Data that exists for the life of the application,
shared by all concurrent users—including instances with different
initialization parameters
• Request attributes : Data passed to other servlets invoked by
the RequestDispatcher
• Session attributes : Data that persists through all future requests
for the current user
• Context attributes : Data shared by all servlets that persists for
the life of the application
5
• In general, concern for thread-safety should be applied only
to instance and class variables.
• Here are the reasons why: All threads share the same
heap,and the heap is where instance variables are stored.
• When multiple threads are accessing the same variable,
there is potential for data corruption, because more than one
thread can access the same instance variable.
• Class variables have a similar problem; they are stored
within the same JVM method area.
• Local variables, method parameters, and return values are
quite different.These variables reside on the Java stack
6
7
Local Variables
public class LocalVariableServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
int count=0;
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count = (init) Math.round(Math.random());
out.println("Count = " + count);
}}
8
Instance Variables
public class InstanceVariableServlet extends HttpServlet
{
int count=0;
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count++;
out.println("Count = " + count);
}
9
synchronized(this) {
count++;
out.println("Count = " + count);
}
10
Synchronizing code can cause:
• Reduction in performance
• Deadlock
• Increased resource utilization
11
public class InstanceVariableServlet
extends HttpServlet{
int count=0;
public void doGet(HttpServletRequest
req,
HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
synchronized(this) {
count++;
}
out.println("Count = " + count);
}
}
This solution works best if
there is a need to protect
shared data.
Another option is to make
the variable Immutable .
This means the variable is
final and cannot change.
12
Class Variables
• Class variables , or static variables, are shared among all
instances of a servlet.
• It is a misconception to think a server will create only one
instance of a particular servlet.
• The truth is, the server can create a new instance of the same
servlet for each registered name defined. Within the web.xml
file, a single servlet can be registered under multiple names.
13
14
public class ClassVariableServlet
extends HttpServlet{
int count;
static HashMap instances = new
HashMap();
static int classCount;
public void doGet(HttpServletRequest
req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count++;
out.println("Since loading, the “ +
req.getServletPath() +
“ instance has been accessed " +
count + " times.");
instances.put(this, this);
out.println("There are currently " +
instances.size() + " instances.");
classCount++;
out.println("Across all instances, the " +
"ClassVariableServlet class has been "
+
"accessed " + classCount + "times.");
}
}
15
A single instance
16
A second instance
17
The third instance
For each registered name, a servlet can have unique init parameters.
Consequently, multiple instances of the same servlet can have different
initialization attributes.
18
Request Attributes
• When a servlet attempts to use another servlet to process part
or all of a response, a RequestDispatcher is used.
• Manually handling servlet-to-servlet communication would be a
difficult task to manage, especially in a multithreaded
environment.
• The RequestDispatcher object is designed to streamline the
process and ensure that concurrency problems do not occur.
19
public class CallingServlet extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
ImageIcon icon =
(ImageIcon)req.getParameter(“icon”);
req.setAttribute(“logo”, icon);
String display = “/servlet/TargetServlet”;
RequestDispatcher dispatcher =
req.getRequestDispatcher(display);
dispatcher.forward(req, res);
To dispatch a request to a resource outside the current servlet context, you must use
the ServletContext.getRequestDispatcher(String path) method.
20
The logic rests on two critical points:
• Dispatched requests must run in the same:
> Servlet engine
> JVM
> Thread
• Dispatcher parameter values are not shared among
threads within a single JVM.
21
Session Attributes
• Because a session is created by the container and associated
with each client through its request object, threading is handled
internally and is quite safe.
• A servlet uses the HttpServletRequest method getSession() to
retrieve the current session. That value should be stored in a
local variable to avoid concurrency issues.
22
Context Attributes
• the ServletContext is an object that provides global data
to an entire application. This global data is referred to as
context attributes.
• If a servlet needs to acquire the port number used to
access the main database, it would invoke the
getServletContext() method to first get a handle to the
application’s context
23
<web-app>
<context-param> <param-name> driver</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
<param-name>databaseProtocol</param-name>
<param-value>jdbc:oracle://dbServer1:1521</param-value>
</context-param>
…
</web-app>
ServletContext context = getServletContext();
String driver =
(String)context.getAttribute(“driver”);
try {
Class.forName(driver);
Connection con = DriverManager.getConnection(
context.getAttribute(“databaseProtocol”) +
“CustomerListDB”);
…
} catch (ClassNotFoundException e) {
out.println(“Unable to load driver”);
} catch (SQLException e) {
out.println(e.getMessage());
24
• If thread A calls setAttribute(…) and changes the value of the
driver attribute, thread B will access the new driver when
getAttribute(“driver”) is called.
• This does not mean that context attributes are not thread-safe,
because the behavior is expected and normal.
• Problems arise if during the implementation of the
setAttribute(…) method, another thread calls setAttribute(…)
on the same name.
• If the method setAttribute(…) is not synchronized, there is
potential for concurrency problems. Most server applications
offer this feature; however, it is not mandated,nor is it
guaranteed.
• So in summary, we can say context attributes are fairly thread-
safe, because they are usually set in the web.xml file and most
servers do synchronize the setAttribute(…) method.
25
Single-Threaded Servlets
• One solution to preventing threading problems within
servlets is to limit the number of threads that can access a
single servlet to one.
• This can bedone by having the servlet implement the
SingleThreadModel interface.
• There are no methods that must be implemented. Instead,
the interface is used as a flag to notify the container how to
handle the servlet life cycle.
• As per the API specifications, a servlet that implements the
SingleThreadModel is “guaranteed” to allow only one thread
access to the service() method at a time.
26
The benefit of this model is that each
thread has access to its own instance
variables for the servlet.
27
threading issues extend beyond instance
variables.
28
Single versus Multithreaded Servlets

Más contenido relacionado

La actualidad más candente

Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming conceptsrahuld115
 
AI 7 | Constraint Satisfaction Problem
AI 7 | Constraint Satisfaction ProblemAI 7 | Constraint Satisfaction Problem
AI 7 | Constraint Satisfaction ProblemMohammad Imam Hossain
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingMoutaz Haddara
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engineDuoyi Wu
 
04 brute force
04 brute force04 brute force
04 brute forceHira Gul
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back trackingTech_MX
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in pythonLifna C.S
 
Open addressiing &amp;rehashing,extendiblevhashing
Open addressiing &amp;rehashing,extendiblevhashingOpen addressiing &amp;rehashing,extendiblevhashing
Open addressiing &amp;rehashing,extendiblevhashingSangeethaSasi1
 
Access to non local names
Access to non local namesAccess to non local names
Access to non local namesVarsha Kumar
 
Lectures 1,2,3
Lectures 1,2,3Lectures 1,2,3
Lectures 1,2,3alaa223
 
Genetic algorithm ppt
Genetic algorithm pptGenetic algorithm ppt
Genetic algorithm pptMayank Jain
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECSreedhar Chowdam
 
pattern classification
pattern classificationpattern classification
pattern classificationRanjan Ganguli
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 

La actualidad más candente (20)

Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming concepts
 
AI 7 | Constraint Satisfaction Problem
AI 7 | Constraint Satisfaction ProblemAI 7 | Constraint Satisfaction Problem
AI 7 | Constraint Satisfaction Problem
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 
04 brute force
04 brute force04 brute force
04 brute force
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back tracking
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
Open addressiing &amp;rehashing,extendiblevhashing
Open addressiing &amp;rehashing,extendiblevhashingOpen addressiing &amp;rehashing,extendiblevhashing
Open addressiing &amp;rehashing,extendiblevhashing
 
Access to non local names
Access to non local namesAccess to non local names
Access to non local names
 
Lectures 1,2,3
Lectures 1,2,3Lectures 1,2,3
Lectures 1,2,3
 
Branch and bound
Branch and boundBranch and bound
Branch and bound
 
Genetic algorithm ppt
Genetic algorithm pptGenetic algorithm ppt
Genetic algorithm ppt
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
pattern classification
pattern classificationpattern classification
pattern classification
 
Delegates in C#
Delegates in C#Delegates in C#
Delegates in C#
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
Backtracking
BacktrackingBacktracking
Backtracking
 

Similar a SCWCD : Thread safe servlets : CHAP : 8

SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4Ben Abdallah Helmi
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
06 response-headers
06 response-headers06 response-headers
06 response-headerssnopteck
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletFahmi Jafar
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsFulvio Corno
 
JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0Arun Gupta
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontrackingvamsi krishna
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Arun Gupta
 
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Arun Gupta
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSPGary Yeh
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentjoearunraja2
 

Similar a SCWCD : Thread safe servlets : CHAP : 8 (20)

Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Servlets
ServletsServlets
Servlets
 
JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
 
Servlet
Servlet Servlet
Servlet
 
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
Servlets 3.0 - Asynchronous, Easy, Extensible @ Silicon Valley Code Camp 2010
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 

Más de Ben Abdallah Helmi

SCWCD : Java server pages CHAP : 9
SCWCD : Java server pages  CHAP : 9SCWCD : Java server pages  CHAP : 9
SCWCD : Java server pages CHAP : 9Ben Abdallah Helmi
 
SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3Ben Abdallah Helmi
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2Ben Abdallah Helmi
 
SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6Ben Abdallah Helmi
 
SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5Ben Abdallah Helmi
 
SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3Ben Abdallah Helmi
 
SCWCD : The servlet model : CHAP : 2
SCWCD  : The servlet model : CHAP : 2SCWCD  : The servlet model : CHAP : 2
SCWCD : The servlet model : CHAP : 2Ben Abdallah Helmi
 
SCWCD : The web client model : CHAP : 1
SCWCD  : The web client model : CHAP : 1SCWCD  : The web client model : CHAP : 1
SCWCD : The web client model : CHAP : 1Ben Abdallah Helmi
 
SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11Ben Abdallah Helmi
 
Ejb3 3-message-driven-beans fr
Ejb3 3-message-driven-beans frEjb3 3-message-driven-beans fr
Ejb3 3-message-driven-beans frBen Abdallah Helmi
 

Más de Ben Abdallah Helmi (19)

The Data Warehouse .pdf
The Data Warehouse .pdfThe Data Warehouse .pdf
The Data Warehouse .pdf
 
Transaction design patterns
Transaction design patternsTransaction design patterns
Transaction design patterns
 
SCWCD : Java server pages CHAP : 9
SCWCD : Java server pages  CHAP : 9SCWCD : Java server pages  CHAP : 9
SCWCD : Java server pages CHAP : 9
 
SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2
 
SCWCD : The web client model
SCWCD : The web client modelSCWCD : The web client model
SCWCD : The web client model
 
SCWCD : Secure web : CHAP : 7
SCWCD : Secure web : CHAP : 7SCWCD : Secure web : CHAP : 7
SCWCD : Secure web : CHAP : 7
 
SCWCD : Secure web
SCWCD : Secure webSCWCD : Secure web
SCWCD : Secure web
 
SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6
 
SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5
 
SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3
 
SCWCD : The servlet model : CHAP : 2
SCWCD  : The servlet model : CHAP : 2SCWCD  : The servlet model : CHAP : 2
SCWCD : The servlet model : CHAP : 2
 
SCWCD : The web client model : CHAP : 1
SCWCD  : The web client model : CHAP : 1SCWCD  : The web client model : CHAP : 1
SCWCD : The web client model : CHAP : 1
 
SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11
 
Ejb3 3-message-driven-beans fr
Ejb3 3-message-driven-beans frEjb3 3-message-driven-beans fr
Ejb3 3-message-driven-beans fr
 
Ejb3 2-session-beans fr
Ejb3 2-session-beans frEjb3 2-session-beans fr
Ejb3 2-session-beans fr
 
Ejb3 1-server-setup fr
Ejb3 1-server-setup frEjb3 1-server-setup fr
Ejb3 1-server-setup fr
 
Axis2 services fr
Axis2 services frAxis2 services fr
Axis2 services fr
 
Axis2 clients fr
Axis2 clients frAxis2 clients fr
Axis2 clients fr
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 

Último (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

SCWCD : Thread safe servlets : CHAP : 8

  • 1. 1 Thread-Safe Servlets Helmi ben abdallah @rchitect JEE
  • 2. 2 THE FOLLOWING SUN CERTIFIED WEB COMPONENT DEVELOPER FOR J2EE PLATFORM EXAM OBJECTIVES COVERED IN THIS CHAPTER: 7.1 Identify which attribute scopes are thread-safe: Local variables Instance variables Class variables Request attributes Session attributes Context attributes 7.2 Identify correct statements about differences between the multithreaded and single-threaded servlet models. 7.3 Identify the interface used to declare that a servlet must use the single thread model.
  • 3. 3 • Threads seem to be a topic that most developers wish to avoid but can’t. • In a single-threaded environment, ensuring the integrity of a Java class is as easy as making all instance variables private and providing public accessor or mutator methods. • In a multithreaded environment, achieving a “thread- safe” application is a bit more complex. • Servlets are intrinsically multithreaded : a single instance can be accessed by more than one thread. Because servlets, by their nature, are designed for multiple users, creating a thread-safe environment is a vital key to the success of the application
  • 4. 4 Attributes • Local variables : Short-term values that are often used as loop iterators. • Instance variables : Data that persists for the life of the servlet, shared by all concurrent users. • Class variables :Data that exists for the life of the application, shared by all concurrent users—including instances with different initialization parameters • Request attributes : Data passed to other servlets invoked by the RequestDispatcher • Session attributes : Data that persists through all future requests for the current user • Context attributes : Data shared by all servlets that persists for the life of the application
  • 5. 5 • In general, concern for thread-safety should be applied only to instance and class variables. • Here are the reasons why: All threads share the same heap,and the heap is where instance variables are stored. • When multiple threads are accessing the same variable, there is potential for data corruption, because more than one thread can access the same instance variable. • Class variables have a similar problem; they are stored within the same JVM method area. • Local variables, method parameters, and return values are quite different.These variables reside on the Java stack
  • 6. 6
  • 7. 7 Local Variables public class LocalVariableServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { int count=0; res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count = (init) Math.round(Math.random()); out.println("Count = " + count); }}
  • 8. 8 Instance Variables public class InstanceVariableServlet extends HttpServlet { int count=0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Count = " + count); }
  • 10. 10 Synchronizing code can cause: • Reduction in performance • Deadlock • Increased resource utilization
  • 11. 11 public class InstanceVariableServlet extends HttpServlet{ int count=0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); synchronized(this) { count++; } out.println("Count = " + count); } } This solution works best if there is a need to protect shared data. Another option is to make the variable Immutable . This means the variable is final and cannot change.
  • 12. 12 Class Variables • Class variables , or static variables, are shared among all instances of a servlet. • It is a misconception to think a server will create only one instance of a particular servlet. • The truth is, the server can create a new instance of the same servlet for each registered name defined. Within the web.xml file, a single servlet can be registered under multiple names.
  • 13. 13
  • 14. 14 public class ClassVariableServlet extends HttpServlet{ int count; static HashMap instances = new HashMap(); static int classCount; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading, the “ + req.getServletPath() + “ instance has been accessed " + count + " times."); instances.put(this, this); out.println("There are currently " + instances.size() + " instances."); classCount++; out.println("Across all instances, the " + "ClassVariableServlet class has been " + "accessed " + classCount + "times."); } }
  • 17. 17 The third instance For each registered name, a servlet can have unique init parameters. Consequently, multiple instances of the same servlet can have different initialization attributes.
  • 18. 18 Request Attributes • When a servlet attempts to use another servlet to process part or all of a response, a RequestDispatcher is used. • Manually handling servlet-to-servlet communication would be a difficult task to manage, especially in a multithreaded environment. • The RequestDispatcher object is designed to streamline the process and ensure that concurrency problems do not occur.
  • 19. 19 public class CallingServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ImageIcon icon = (ImageIcon)req.getParameter(“icon”); req.setAttribute(“logo”, icon); String display = “/servlet/TargetServlet”; RequestDispatcher dispatcher = req.getRequestDispatcher(display); dispatcher.forward(req, res); To dispatch a request to a resource outside the current servlet context, you must use the ServletContext.getRequestDispatcher(String path) method.
  • 20. 20 The logic rests on two critical points: • Dispatched requests must run in the same: > Servlet engine > JVM > Thread • Dispatcher parameter values are not shared among threads within a single JVM.
  • 21. 21 Session Attributes • Because a session is created by the container and associated with each client through its request object, threading is handled internally and is quite safe. • A servlet uses the HttpServletRequest method getSession() to retrieve the current session. That value should be stored in a local variable to avoid concurrency issues.
  • 22. 22 Context Attributes • the ServletContext is an object that provides global data to an entire application. This global data is referred to as context attributes. • If a servlet needs to acquire the port number used to access the main database, it would invoke the getServletContext() method to first get a handle to the application’s context
  • 23. 23 <web-app> <context-param> <param-name> driver</param-name> <param-value>oracle.jdbc.driver.OracleDriver</param-value> <param-name>databaseProtocol</param-name> <param-value>jdbc:oracle://dbServer1:1521</param-value> </context-param> … </web-app> ServletContext context = getServletContext(); String driver = (String)context.getAttribute(“driver”); try { Class.forName(driver); Connection con = DriverManager.getConnection( context.getAttribute(“databaseProtocol”) + “CustomerListDB”); … } catch (ClassNotFoundException e) { out.println(“Unable to load driver”); } catch (SQLException e) { out.println(e.getMessage());
  • 24. 24 • If thread A calls setAttribute(…) and changes the value of the driver attribute, thread B will access the new driver when getAttribute(“driver”) is called. • This does not mean that context attributes are not thread-safe, because the behavior is expected and normal. • Problems arise if during the implementation of the setAttribute(…) method, another thread calls setAttribute(…) on the same name. • If the method setAttribute(…) is not synchronized, there is potential for concurrency problems. Most server applications offer this feature; however, it is not mandated,nor is it guaranteed. • So in summary, we can say context attributes are fairly thread- safe, because they are usually set in the web.xml file and most servers do synchronize the setAttribute(…) method.
  • 25. 25 Single-Threaded Servlets • One solution to preventing threading problems within servlets is to limit the number of threads that can access a single servlet to one. • This can bedone by having the servlet implement the SingleThreadModel interface. • There are no methods that must be implemented. Instead, the interface is used as a flag to notify the container how to handle the servlet life cycle. • As per the API specifications, a servlet that implements the SingleThreadModel is “guaranteed” to allow only one thread access to the service() method at a time.
  • 26. 26 The benefit of this model is that each thread has access to its own instance variables for the servlet.
  • 27. 27 threading issues extend beyond instance variables.