Nitin Kulkarni wrote:

> HI Chris
>
> Could you please elaborate a bit on this. I was/am under the impression that
> since init() is going to get called only once in a servlets life time anything
> we write in that is going to be thread safe. But your mails seems to say that it
> is/may not be so always.
> Also what does ' the diff types of JDBC implementations'  mean. Here again I am
> under the impression that JDBC since it is provided by sun it has to be same
> only we need diff drivers to connect to diff databases.
> Please throw some light on this
>

The init() method indeed "thread safe" in the manner you are talking about.  In
other words, the servlet engine guarantees that there will be only one thread in the
init() method, and that no calls to the service() method will occur until init()
returns.

The place where you are still not necessarily safe is that, once the service() calls
start happening, the various calls will be sharing the single JDBC connection that
you created in the init() method.  Some JDBC drivers will handle this correctly, in
the sense that you can have multiple statements and result sets open on the same
connection at the same time.  However, you are almost certain to run into
transaction problems if your database supports transactions (MySQL doesn't, for
example, but Oracle/Sybase/Postgres/etc. do).  If you do a COMMIT or ROLLBACK in the
thread of one service() call, it will affect the statements currently executing in
*all* of them.

The solution is to use a "connection pool" instead of a single connection.  As the
name implies, you open a set of connections in the init() method, instead of just
one.  Whenever a service() method call needs to access the database, it does
essentially this:
* Allocates one of the connections from the pool
* Does its JDBC calls on the connection that
  is, for the moment, dedicated to that thread.
* Returns the connection to the pool.

A good analogy to this is checking books out of a library -- the book is available
to everyone, but can be checked out and read by only one person at a time.

There has been substantial discussion about connection pools, including suggestions
on some freely available ones, on this list.  I suggest you peruse the archives
(http://archives.java.sun.com) and look for messages that have "connection pool" or
"connection broker" in their subjects.

>
> Thanks
>
> Nitin
>

Craig McClanahan

___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".

Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html

Reply via email to