Java Reference
In-Depth Information
To make matters worse, our intuition may often be wrong on which classes are “probably
thread-safe” and which are not. As an example, java.text.SimpleDateFormat isn't
thread-safe, but the Javadoc neglected to mention this until JDK 1.4. That this particular class
isn't thread-safe comes as a surprise to many developers. How many programs mistakenly
create a shared instance of a nonthread-safe object and used it from multiple threads, unaware
that this might cause erroneous results under heavy load?
The problem with SimpleDateFormat could be avoided by not assuming a class is
thread-safe if it doesn't say so. On the other hand, it is impossible to develop a servlet-based
application without making some pretty questionable assumptions about the thread safety of
container-provided objects like HttpSession . Don't make your customers or colleagues
have to make guesses like this.
4.5.1. Interpreting Vague Documentation
Many Java technology specifications are silent, or at least unforthcoming, about thread safety
guarantees and requirements for interfaces such as ServletContext , HttpSession ,
or DataSource . [9] Since these interfaces are implemented by your container or database
vendor, you often can't look at the code to see what it does. Besides, you don't want to rely
on the implementation details of one particular JDBC driver—you want to be compliant with
the standard so your code works properly with any JDBC driver. But the words “thread” and
“concurrent” do not appear at all in the JDBC specification, and appear frustratingly rarely in
the servlet specification. So what do you do?
You are going to have to guess. One way to improve the quality of your guess is to interpret
the specification from the perspective of someone who will implement it (such as a contain-
er or database vendor), as opposed to someone who will merely use it. Servlets are always
called from a container-managed thread, and it is safe to assume that if there is more than one
such thread, the container knows this. The servlet container makes available certain objects
that provide service to multiple servlets, such as HttpSession or ServletContext . So
the servlet container should expect to have these objects accessed concurrently, since it has
created multiple threads and called methods like Servlet.service from them that could
reasonably be expected to access the ServletContext .
Since it is impossible to imagine a single-threaded context in which these objects would be
useful, one has to assume that they have been made thread-safe, even though the specific-
ation does not explicitly require this. Besides, if they required client-side locking, on what
lock should the client code synchronize? The documentation doesn't say, and it seems absurd
to guess. This “reasonable assumption” is further bolstered by the examples in the specific-
Search WWH ::




Custom Search