• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Servlets and Threading

 
Pete Barr
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
Thanks
Pete
 
Cameron Park
Ranch Hand
Posts: 371
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic