XML technologies / XSLT / Java and XSLT / Servlet basics and XSLT / Servlets and threading problems
(Excerpt from “Java und XSLT” by Eric M. Burke)
Servlets must serve several clients simultaneously. Java’s built-in multithreading is a major advantage for server applications, especially over traditional CGI. The tradeoff is the challenge of writing concurrent programs without corrupting data. This page introduces servlet threading concerns.
The servlet threading model
In the standard model, a client request reaches the servlet’s method service( ). In class HttpServlet, method service( ) determines the HTTP request type and calls doGet( ) or doPost( ) accordingly. For several clients, these methods serve each in a separate thread. Since most servlets extend HttpServlet, ensure methods service( ), doGet( ) and doPost( ) can serve clients concurrently.
Before any request is handled, servlet method init( ) is called. The servlet API requires that only one thread call it and that it finish successfully before other threads may call service( ). Thus method init( ) needs no threading precautions. Things become harder afterward.
One simple way to make a method thread-safe is to declare it synchronized. Method doGet( ) would look like this:
protected synchronized void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
...
}Keyword synchronized requires every calling thread to acquire a lock on the servlet object. Other clients wait until the first releases it. If method doGet( ) takes 0.5 seconds and 100 more users need access, many visitors wait about a minute in the lock queue.
This is undesirable. Alternatively, the servlet can implement interface javax.servlet.SingleThreadModel as follows:
public class MeinServlet extends HttpServlet implements SingleThreadModel {
...
}Interface SingleThreadModel is a marker declaring no methods. It tells the container that the servlet is not thread-safe and can handle only one request at a time in method service( ). A typical container creates a pool of instances, each handling one request at a time.
This is somewhat better than synchronizing methods doGet( ) and doPost( ), but instantiates multiple copies, using more memory without solving every concurrency problem. Shared resources such as files or variables declared static still allow concurrent modification.
Thread-safety tips
Most servlet threading problems arise when several threads modify one resource, such as a file or shared variable. The behavior becomes unpredictable and hard to diagnose. Another problem is a deadlock, where two threads each hold a lock the other needs. Performance also matters: synchronizing a method can seriously reduce throughput.
The best approach is not to use interface SingleThreadModel but to synchronize access to method service( ). The servlet can then handle concurrent requests, but you must avoid several threads modifying a shared resource. These tips offer guidance.
Tip 1: Local variables are safe
Servlet instance variables often cause trouble. Consider:
public class HomeServlet extends HttpServlet {
private Customer currentCust;
Servlets und Probleme mit Threads | 227
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException {
HttpSession session = request.getSession(true);
currentCust = (Customer) session.getAttribute("cust");
currentCust.setLastAccessedTime(new Date( ));
...
}
}Here, field currentCust is obtained through HttpSession when a new client calls method doGet( ). A second thread calling shortly afterward overwrites field currentCust before the first thread finishes. Many threads might enter method doGet( ) almost simultaneously, each changing reference currentCust.
Simply declare currentCust as a local variable:
public class HomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException {
HttpSession session = request.getSession(true);
Customer currentCust = (Customer) session.getAttribute("cust");
currentCust.setLastAccessedTime(new Date( ));
...
}
}This solves the problem because each Java thread has its own copy of local variables.
Tip 2: Immutable objects are safe
Several threads changing an object can race. Consider:
public class Person {
private String firstName;
private String lastName;
public void setName(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
...get-Methoden weggelassen
}If two threads call method setName( ) at about the same time, this can happen:
Thread A sets the first name to Bill, then thread B interrupts.
Thread B sets first name George and last name Bush.
Thread A resumes and sets last name Clinton.
The unintended result is George Clinton. Even if method setName( ) is declared synchronized, every getter would also need to be declared synchronized.
Another option is making the object immutable. Class Person would become:
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName( ) { return this.firstName; }
public String getLastName( ) { return this.lastName; }
}Since instances of Person cannot change, their methods need not be synchronized. This allows concurrent reading. The drawback is that existing objects cannot be changed; create a new Person object when needed. This is essentially how java.lang.String works.
Immutability is not always appropriate, but useful for small helper classes found in most applications.
Tip 3: Provide one access point
For a shared resource, such as a file to modify, consider a facade: one class controlling access and providing a synchronization point. This example wraps a data source containing Customer objects. Class Customer should be immutable so an instance of Customer can be manipulated only through this API:
public class CustomerSource {
public static synchronized Customer getCustomer(String id) {
// Lese die Kundendaten aus einer Datei
// oder einer Datenbank...
}
public static synchronized Customer createCustomer( ) {
// erzeuge einen neuen Kunden in der Datei
// bzw. der Datenbank und liefere ihn zurück...
}
public static synchronized void deleteCustomer(String id) {
// ...
}
}This simple approach suits small applications. Methods doGet( ) and doPost( ) can use class CustomerSource without corrupting data. If methods on CustomerSource are slow, clients again wait for access to the underlying structure.
Tip 4: Understand the Templates interface
Several threads can share an instance of javax.xml.transform.Templates, making it suitable as a servlet instance variable:
public class MyServlet extends HttpServlet {
private Templates homePageStylesheet;
...
}Instances of javax.xml.transform.Transformer are not thread-safe and should be local variables in methods doGet() and doPost():
public class MyServlet extends HttpServlet {
private Templates homePageStylesheet;
public void init( ) throws UnavailableException {
... erzeuge eine Instanz von Templates
}
protected void doGet( ) {
Transformer trans = homePageStylesheet.newTransformer( );
... benutze die Instanz von Transformer als lokale Variable
}
}
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Java und XSLT” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de