SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
Fahad Golra
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
sourabh aggarwal
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
Emprovise
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
David Gómez García
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
Sasidhar Kothuru
 
Geneva JUG - Cassandra for Java Developers
Geneva JUG - Cassandra for Java DevelopersGeneva JUG - Cassandra for Java Developers
Geneva JUG - Cassandra for Java Developers
Michaël Figuière
 
Java servlets
Java servletsJava servlets
Java servlets
lopjuan
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
Katy Slemon
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
Venkateswara Rao N
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
EclipseCon - Building an IDE for Apache Cassandra
EclipseCon - Building an IDE for Apache CassandraEclipseCon - Building an IDE for Apache Cassandra
EclipseCon - Building an IDE for Apache Cassandra
Michaël Figuière
 
Commons Pool and DBCP
Commons Pool and DBCPCommons Pool and DBCP
Commons Pool and DBCP
Phil Steitz
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Database connect
Database connectDatabase connect
Database connect
Yoga Raja
 
Dropwizard
DropwizardDropwizard
Dropwizard
Scott Leberknight
 
50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes
Antonio Goncalves
 
ChtiJUG - Cassandra 2.0
ChtiJUG - Cassandra 2.0ChtiJUG - Cassandra 2.0
ChtiJUG - Cassandra 2.0
Michaël Figuière
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
Yoga Raja
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
Fahad Golra
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
sourabh aggarwal
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
Emprovise
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
David Gómez García
 
Web Technologies -- Servlets 4 unit slides
Web Technologies -- Servlets   4 unit slidesWeb Technologies -- Servlets   4 unit slides
Web Technologies -- Servlets 4 unit slides
Sasidhar Kothuru
 
Geneva JUG - Cassandra for Java Developers
Geneva JUG - Cassandra for Java DevelopersGeneva JUG - Cassandra for Java Developers
Geneva JUG - Cassandra for Java Developers
Michaël Figuière
 
Java servlets
Java servletsJava servlets
Java servlets
lopjuan
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
Katy Slemon
 
Java Servlet
Java ServletJava Servlet
Java Servlet
Yoga Raja
 
EclipseCon - Building an IDE for Apache Cassandra
EclipseCon - Building an IDE for Apache CassandraEclipseCon - Building an IDE for Apache Cassandra
EclipseCon - Building an IDE for Apache Cassandra
Michaël Figuière
 
Commons Pool and DBCP
Commons Pool and DBCPCommons Pool and DBCP
Commons Pool and DBCP
Phil Steitz
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Database connect
Database connectDatabase connect
Database connect
Yoga Raja
 
50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes
Antonio Goncalves
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
Yoga Raja
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 

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

SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
team11vgnt
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4
Ben Abdallah Helmi
 
servlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivityservlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
GWTcon
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
snopteck
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi 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 applications
Fulvio Corno
 
18CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-318CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-3
Sivakumar M
 
JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0
Arun Gupta
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
vamsi 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 2010
Arun Gupta
 
Servlet
Servlet Servlet
Servlet
Dhara Joshi
 
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
Arun Gupta
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
Fulvio Corno
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
Fulvio Corno
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Gary 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, environment
joearunraja2
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
Jyothishmathi Institute of Technology and Science Karimnagar
 
SERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servletsSERVLETS (2).pptxintroduction to servlet with all servlets
SERVLETS (2).pptxintroduction to servlet with all servlets
RadhikaP41
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4
Ben Abdallah Helmi
 
servlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivityservlets sessions and cookies, jdbc connectivity
servlets sessions and cookies, jdbc connectivity
snehalatha790700
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
GWTcon
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
snopteck
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
Fahmi 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 applications
Fulvio Corno
 
18CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-318CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-3
Sivakumar M
 
JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0
Arun Gupta
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
ssbd6985
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
vamsi 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 2010
Arun 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 2010
Arun Gupta
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Gary 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, environment
joearunraja2
 
Ad

More from Ben Abdallah Helmi (19)

The Data Warehouse .pdf
The Data Warehouse .pdfThe Data Warehouse .pdf
The Data Warehouse .pdf
Ben Abdallah Helmi
 
Transaction design patterns
Transaction design patternsTransaction design patterns
Transaction design patterns
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 : 9
Ben Abdallah Helmi
 
SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3
Ben Abdallah Helmi
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2
Ben Abdallah Helmi
 
SCWCD : The web client model
SCWCD : The web client modelSCWCD : The web client model
SCWCD : The web client model
Ben Abdallah Helmi
 
SCWCD : Secure web : CHAP : 7
SCWCD : Secure web : CHAP : 7SCWCD : Secure web : CHAP : 7
SCWCD : Secure web : CHAP : 7
Ben Abdallah Helmi
 
SCWCD : Secure web
SCWCD : Secure webSCWCD : Secure web
SCWCD : Secure web
Ben Abdallah Helmi
 
SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6
Ben Abdallah Helmi
 
SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5
Ben Abdallah Helmi
 
SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3
Ben Abdallah Helmi
 
SCWCD : The servlet model : CHAP : 2
SCWCD  : The servlet model : CHAP : 2SCWCD  : The servlet model : CHAP : 2
SCWCD : The servlet model : CHAP : 2
Ben 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 : 1
Ben Abdallah Helmi
 
SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11
Ben Abdallah Helmi
 
Ejb3 3-message-driven-beans fr
Ejb3 3-message-driven-beans frEjb3 3-message-driven-beans fr
Ejb3 3-message-driven-beans fr
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 : 9
Ben Abdallah Helmi
 
SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3SCWCD : Servlet web applications : CHAP : 3
SCWCD : Servlet web applications : CHAP : 3
Ben Abdallah Helmi
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2
Ben Abdallah Helmi
 
SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6SCWCD : Session management : CHAP : 6
SCWCD : Session management : CHAP : 6
Ben Abdallah Helmi
 
SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5
Ben Abdallah Helmi
 
SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3SCWCD : Servlet web applications : CHAP 3
SCWCD : Servlet web applications : CHAP 3
Ben Abdallah Helmi
 
SCWCD : The servlet model : CHAP : 2
SCWCD  : The servlet model : CHAP : 2SCWCD  : The servlet model : CHAP : 2
SCWCD : The servlet model : CHAP : 2
Ben 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 : 1
Ben Abdallah Helmi
 
SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11SCWCD : Web tier design CHAP : 11
SCWCD : Web tier design CHAP : 11
Ben Abdallah Helmi
 
Ejb3 3-message-driven-beans fr
Ejb3 3-message-driven-beans frEjb3 3-message-driven-beans fr
Ejb3 3-message-driven-beans fr
Ben Abdallah Helmi
 
Ad

Recently uploaded (20)

Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 

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.