File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Servlets and Threading Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Servlets and Threading" Watch "Servlets and Threading" New topic

Servlets and Threading

Pete Barr

Joined: Jul 07, 2001
Posts: 3
Hi all,
If a servlet is written that accesses (but does not update) a database is threading necessary? (assuming that the servlet is intended to serve multiple clients concurrently)
Cameron Park
Ranch Hand

Joined: Apr 06, 2001
Posts: 371
I have the same question. I was making a Connection Pool, and it just dawned on me, if each of the Connection should be an individual Thread. But no, each Connection does not need to explicitly implment Runnable or extend Thread. Maybe it was already done within the COnnection class itself.
SoonAnn Lim
Ranch Hand

Joined: Jun 21, 2001
Posts: 155
The fact is, when you deploy your servlet, one instance of your servlet will be created. When request comes in, each request will be handled by a thread according to servlet's specification. So each thread will have one connection to the database. (correct me if i am wrong)
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

Put it this way.. it is not so much a matter of 'are threads necessary'... as it is of ' you will get threads, because servlets are multithreaded'

So if you have database access code, you must decide whether you should make this a synchronized block or not. I'm not really that knowledgable about databases, but I understand there is such a thing as a read lock.

So imagine that one user hits the servlet and enters the method that reads from the database. A millisecond later, a second user also makes the same request. Will the second user's read fail because the first user has a read lock on that table? Hopefully not, maybe I'm shouting "the sky is falling, the sky is falling."
Vlad Patryshev
Ranch Hand

Joined: Jun 30, 2001
Posts: 61
One cannot expect that a servlet runs as a singleton. There will be many many instances of a servlet, each in its own thread.
But if you are using a database, in this context I would advise to use EJB; then bean and connection pool becomes Someone Else's Problem.

Thanks,<br />Vlad
I agree. Here's the link:
subject: Servlets and Threading
It's not a secret anymore!