• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question from jwebplus

 
Vedhas Pitkar
Ranch Hand
Posts: 445
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question ID :999281592677
Consider the following servlet...
import javax.servlet.*;
import javax.servlet.http.*:
public class SafeServlet extends HttpServlet implements SingleThreadModel
{
StringBuffer safeBuffer = new StringBuffer("I am thread safe!");
public void doGet(HttpServletRequest req, HttpServletResponse res)
{
safeBuffer.append(req.getRemoteAddr());
}
}
Which of the following statements is correct?
a. Remote addresses of ALL the requests will be appended to same StringBuffer Object
b. It'll try to append Remote addresses of ALL the requests to same StringBuffer Object but may get corrupted because of simultaneous requests.
c. For each request, anew servlet instance will be created & so the same StringBuffer will not contain all the addresses.
d. All remote addresses will beappended successfully but not to the same StringBuffer.
I answered c but the correct answer was given as d .But it is upto the server to make instances ,as such server-specific.Any comments?
 
Rishi Yagnik
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
i fill ans should be c only
Rishi
 
Bart Laeremans
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
D is indeed correct.
On some containers a Thread-safe servlet is not be instantiated for every request. A kind of pool will be used so that the same servlet is not used concurrently, but will be reused is the servlet is not in use by another request.
Some containers might create new instances for every request, but the only certainty that U have is that multiple request don't use the same servlet at the same time.
 
friso jonge
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
right answer is D.
Like said above, the container creates a pool of servlet instances. Since the stringbuffer is an instance variable (and not a class static variable), it does exist for each instance. So the addresses are added to the stringbuffer instance of the pooled resource. Not all requests use the same servlet instance !!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic