background image

Accessing Databases

<< Controlling Concurrent Access to Shared Resources | The Database Access Class >>
<< Controlling Concurrent Access to Shared Resources | The Database Access Class >>

Accessing Databases

Multiple threads within a web component accessing instance variables. A web container will
typically create a thread to handle each request. If you want to ensure that a servlet instance
handles only one request at a time, a servlet can implement the
SingleThreadModel
interface. If a servlet implements this interface, you are guaranteed that no two threads will
execute concurrently in the servlet's service method. A web container can implement this
guarantee by synchronizing access to a single instance of the servlet, or by maintaining a
pool of web component instances and dispatching each new request to a free instance. This
interface does not prevent synchronization problems that result from web components
accessing shared resources such as static class variables or external objects. In addition, the
Servlet 2.4 specification deprecates the SingleThreadModel interface.
When resources can be accessed concurrently, they can be used in an inconsistent fashion. To
prevent this, you must control the access using the synchronization techniques described in the
Threads
lesson in
The Java Tutorial, Fourth Edition
, by Sharon Zakhour et al. (Addison-Wesley,
2006).
The preceding section showed five scoped attributes shared by more than one servlet: bookDB,
cart
, currency, hitCounter, and orderCounter. The bookDB attribute is discussed in the next
section. The cart, currency, and counters can be set and read by multiple multithreaded servlets.
To prevent these objects from being used inconsistently, access is controlled by synchronized
methods. For example, here is the Counter class, located at
tut-install/javaeetutorial5/examples/web/bookstore1/src/java/com/sun/bookstore1/util/:
public class Counter {
private int counter;
public Counter() {
counter = 0;
}
public synchronized int getCounter() {
return counter;
}
public synchronized int setCounter(int c) {
counter = c;
return counter;
}
public synchronized int incCounter() {
return(++counter);
}
}
Accessing Databases
Data that is shared between web components and is persistent between invocations of a web
application is usually maintained by a database. Web components use the Java Persistence API
to access relational databases. The data for Duke's Bookstore is maintained in a database and is
Sharing Information
Chapter 4 · Java Servlet Technology
107