Java Reference
In-Depth Information
ation and official tutorials that show how to access
ServletContext
or
HttpSession
and do not use any client-side synchronization.
On the other hand, the objects placed in the
ServletContext
or
HttpSession
with
setAttribute
are owned by the web application, not the servlet container. The servlet
specification does not suggest any mechanism for coordinating concurrent access to shared
attributes. So attributes stored by the container on behalf of the web application should be
thread-safe or effectively immutable. If all the container did was store these attributes on
behalf of the web application, another option would be to ensure that they are consistently
guarded by a lock when accessed from servlet application code. But because the container
may want to serialize objects in the
HttpSession
for replication or passivation purposes,
and the servlet container can't possibly know your locking protocol, you should make them
thread-safe.
One can make a similar inference about the JDBC
DataSource
interface, which represents
a pool of reusable database connections. A
DataSource
provides service to an application,
and it doesn't make much sense in the context of a singlethreaded application. It is hard to
imagine a use case that doesn't involve calling
getConnection
from multiple threads.
And, as with servlets, the examples in the JDBC specification do not suggest the need for
any client-side locking in the many code examples using
DataSource
. So, even though the
specification doesn't promise that
DataSource
is thread-safe or require container vendors
to provide a thread-safe implementation, by the same “it would be absurd if it weren't” ar-
gument, we have no choice but to assume that
DataSource.getConnection
does not
require additional client-side locking.
On the other hand, we would not make the same argument about the JDBC
Connection
objects dispensed by the
DataSource
, since these are not necessarily intended to be shared
by other activities until they are returned to the pool. So if an activity that obtains a JDBC
Connection
spans multiple threads, it must take responsibility for ensuring that access to
the
Connection
is properly guarded by synchronization. (In most applications, activities
that use a JDBC
Connection
are implemented so as to confine the
Connection
to a spe-
cific thread anyway.)