• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Fundamental servlet question.

 
Siva kandasamy
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
See the servlet below.
"i" is not a static. How come each request I make to this servlet is, incrementing "i" ?

thanks
siva



//: c15:servlets:ThreadServlet.java
// {Depends: j2ee.jar}
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class ThreadServlet extends HttpServlet {
int i;
public void service(HttpServletRequest req,
HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();

synchronized(this) {
try {
Thread.currentThread().sleep(5000);
} catch(InterruptedException e) {
System.err.println("Interrupted");
}
}

out.print("<h1>Finished " + i++ + "</h1>");
out.close();
}

} ///:~
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65124
91
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the container is re-using a single instance of the servlet. That is why you should not use member variables, static or otherwise, unless you want them to be shared across all threads.
 
Siva kandasamy
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bear.

BTW,
In this case, do you see any difference between member variable and static variable ? I don't. Is my understanding is correct ?

Is there any situation, where we have to have more than one instance of same servlet ?

-siva
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65124
91
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Siva kandasamy:
Is there any situation, where we have to have more than one instance of same servlet ?


If you declare more than one <servlet> element in the web.xml using the same class, you will get an instance of the class for each element.
 
Siva kandasamy
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bear.
-siva
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic