0

I wrote a simple Servlet that connects to the DB, retrieves some info end writes a json response. I 'm using tomcat.

Just a couple of question about servlets:

1) As far as I understood the container, if receives simultaneous requests, puts them in a queue and in the end only one Servlet at time is executed, is that true? or the container parallelize the requests using different Servlets instances?

2) In order to connect to the DB,I create the connection in another Class that implements ServletContextListener in the contextInitialized and close it in the contextDestroyed. Is that the correct way? If I want to parallelize should I use different connections , correct?

navy1978
  • 1,411
  • 1
  • 15
  • 35

1 Answers1

1
  1. No, it's not. The requests are executed concurrently, using a single servlet instance. They're only queued if there is no thread available in the tomcat thread pool to handle the request.

  2. No, it's not. Each transaction should get its own connection from a pool of connections (a DataSource, typically exposed in JNDI by Tomcat), do its job with this connection, commit or rollback, and then close the connection to give it back to the pool.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Ok thanks. What do you mean by “using a single setvlet instance” ? In order to be executed concurrently don’t they (servlet instances) need to be one for each request? If there is only one instance how can they be exucuted simultaneously ? – navy1978 Dec 05 '17 at 20:22
  • 1
    Well, multiple threads call the unique servlet object methods concurrently. If you think an object can only be used by one thread at a time, then you need to read a tutorial on threading, because you're really misunderstanding threads. – JB Nizet Dec 05 '17 at 22:23
  • Ok thank you. I got the Thread part. Another small question: About the Datasource I have defined it in Tomcat and I'm using it in the application, but I have I doubt, It's enough to create the connection in the class that implements ServletContextListener or do I have to do the lookup and create the connection for each request? – navy1978 Dec 06 '17 at 18:16
  • Read my answer again. Point 2 says: each transaction should get its own connection from the datasource. If you create a connection once in a listener, and use it everywhere, you clearly don't follow that rule. – JB Nizet Dec 06 '17 at 18:45