• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about servlet initialization, threads, sessions, etc

 
Bobby Pardridge
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to understand how instances of HttpServlet are created and managed in Tomcat.

So far my understanding is that there is one instance of HttpServlet for each user. So if I have the following code:

public class Test extends HttpServlet {

public int x;
public static int y;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
x = x++;
y = y++;
}
}

And I have user1 and user2 make 5 get requests, then for both users the value of x should be 5 and the value of y should be 10.

Am I totally missing something here?

Thanks!
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65216
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bobby Pardridge wrote:Am I totally missing something here?

Yes.

So far my understanding is that there is one instance of HttpServlet for each user

Whatever led you to this understanding needs to be expunged from your source material, as it is completely incorrect.

One instance of the servlet is created. Period. *

So if I have the following code:

You will have endless threading problems.

Bottom line: no instance variables in a servlet. None. Ever.



* There are exceptions, but none that are pertinent at this point.
 
Bobby Pardridge
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I should make all my variables static?

Right now I have a ConcurrentHashMap instance variable in my HttpServlet that I want other classes to be able to read from, which is why I would like to make it static, and I was just wondering what the consequences of doing so would be.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65216
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bobby Pardridge wrote:So I should make all my variables static?

Of course not. That would be even worse!

Your servlets need to be written in a thread-safe manner as only one instance of the servlet will be shared amongst all threads in the web app.

I was just wondering what the consequences of doing so would be.

Endless problems and headaches.

Data that only needs to be known to the current method should be variables declared in the method.

Anything else needs to be stored as a scoped variable in one of request, session or application scopes as appropriate for the life-cycle of the data.

Let me rephrase the bottom line: no class-level variables in a servlet unless they are read-only and (pseudo) final.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic