wood burning stoves 2.0*
The moose likes Servlets and the fly likes Fundamental servlet question. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Fundamental servlet question." Watch "Fundamental servlet question." New topic
Author

Fundamental servlet question.

Siva kandasamy
Ranch Hand

Joined: Dec 31, 2002
Posts: 139
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

Joined: Jan 10, 2002
Posts: 60800
    
  65

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.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Siva kandasamy
Ranch Hand

Joined: Dec 31, 2002
Posts: 139
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

Joined: Jan 10, 2002
Posts: 60800
    
  65

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

Joined: Dec 31, 2002
Posts: 139
Thanks Bear.
-siva
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Fundamental servlet question.
 
Similar Threads
how to use ssi in servlets using apache web server and jserv
servlet is not executing
really simple servlets,but why second one not work
Tomcat problem
Running first example of head first Servlets & JSP