Servlet thread implementation
- Q: Are servlets multi-threaded?
- A: Yes, servlets are normally multi-threaded. The servlet container allocates a thread for each new request for a single servlet without any special programming. Each request thread for your servlet runs as if a single user were accessing it alone, but you can use static variables to store and present information that is common to all threads, like a hit counter for instance.
- Q: What is a service thread and how do I create one?
- A: The most common use of service threads are those used by a servlet container to handle the HTTP request-response process with a Java servlet. Servlet containers use an independent thread of execution so they can process many concurrent requests to many servlets and manage the overall performance of the server. Servlet requests are handled through the
service()
method, so they are named service threads, but other Java applications may use a similar service scheme. Servlet containers automatically create or obtain service threads from a thread pool when a new HTTP request is received, so they do not need to be created explicitly in your servlet code. - Q: How does the container handle concurrent requests?
- A: Servlet containers usually manage concurrent requests by creating a new Java thread for each request. The new thread is given an object reference to the requested servlet, which issues the response through the same thread. This is why it is important to design for concurrency when you write a servlet, because multiple requests may be handled by the same servlet instance.
- Q: Are you saying there is only one servlet instance for all requests?
- A: The way that servlet containers handle servlet requests is not prescribed to this extent; they may use a single servlet, they may use servlet pooling, it depends on the vendor's system architecture. New threads are not necessarily created for every servlet request but may be recycled through a worker thread pool for efficiency. The point is that you should write your servlet code to take account of a multi-threaded context regardless of the container implementation you happen to be using. In other words, you should adhere to the principle of write once, run anywhere.
- Q: Are servlet requests handled first come, first served?
- A: The use of a single servlet to handle multiple requests is usually done with Java threads. For each HTTP request the servlet container assigns a worker thread in which to execute the servlet code and a reference to the relevant servlet instance to call its service methods. The priority order by which the service threads are acquired and process the request depends on the detailed implementation of the servlet container. The natural principle is that it should be first come first served, but the actual execution sequence also depends on the thread scheduling scheme in the Java virtual machine. Servlet containers normally limit the number of service threads that can be run concurrently, so pending requests are typically added to a queue. Once a service thread is assigned to a request, the sequence in which the thread is executed depends on the thread scheduling system of the Java Runtime Environment (JRE). Threads can enter complex stop, start sequences in contention with other service threads, which is why your servlet code needs to be thread safe.
The single thread model
- Q: What is the single threaded model?
- A: Standard servlets are normally handled in a multi-threaded context in the servlet container. A number of virtually simultaneous requests for a single servlet could be handled by different threads using the same servlet instance. Any number of threads could access or modify the static and instance fields of a single servlet instance in an unpredictable sequence. This makes the instance fields of servlets as vulnerable to threading issues as static fields, and modification of shared resources must be considered carefully. If your servlet implements the
SingleThreadModel
interface, it gets a guarantee from the servlet container that any single instance of the servlet will only be accessed by one thread at a time. The container either synchronizes access to the servlet'sservice()
method, or uses a single instance of the servlet drawn from a pool. The single threaded model adds a performance overhead to locking or managing servlet instances, so should not be used lightly. Generally, it is best to ensure synchronized access to servlet resources in your application code. - Q: Why use
SingleThreadedModel
if servlets are multi-threaded? - A: The
SingleThreadedModel
interface is used to ensure the safety of servlets that are vulnerable to thread safety issues. Normally, servlets should be written to run safely in a multi-threaded environment, and are executed in this context. TheSingleThreadedModel
is a way to override the normal multi-threaded execution context of the servlet container. - Q: How do I implement the single threaded model?
- A: To create a servlet that a container will manage on a single threaded basis it must declare that it implements the
javax.servlet.SingleThreadModel
interface. This is a marker interface, there are no extra methods to fulfil, but this is sufficient for the container to identify the type and manage it accordingly.
The servlet container will typically synchronize access to a single instance of the servlet, or create a pool of servlet instances and allocate one request per instance.public
class
SingleThreadServletextends
HttpServletimplements
SingleThreadModel {// Standard HTTP servlet methods
} - Q: Should I use the
SingleThreadedModel
? - A: Not unless you have very good reason. The
SingleThreadedModel
interface has been deprecated, which means that it should not be used and may be removed in a later release of the Java servlet specification and Application Programming Interface (API). It has never really been advisable to implement theSingleThreadedModel
, you should always aim to address thread safety issues in servlets using standard Java programming techniques. - Q: How can I invoke servlet pooling with
SingleThreadedModel
? - A: The
SingleThreadedModel
servlet specification does not require the creation of a pool of servlets. A single threaded model implementation may also synchronize access to a single servlet instance to achieve the same outcome, so that only one request is processed at a time. Apache Tomcat uses the synchronized approach, other servlet containers may use the pooled approach. If you are concerned about the performance impact of synchronized access to the servlet instance, it would be preferable to re-design your servlet so that it does not depend on this mechanism at all. For example, you might create asynchronized
block around the statements that are vulnerable to threading issues. By doing away with the single threaded model, you will minimise the performance impact of thread control.
Servlet thread management
- Q: Can my servlet control the number of threads it accepts?
- A: Your servlet should be designed to be thread safe and not to anticipate any limit to the number of concurrent requests it will receive. You should configure the number of concurrent requests to accept in your servlet container configuration. In Apache Tomcat this property is set in the
server.xml
file'sConnector
element, as below.<Connector
className
="org.apache.catalina.connector.http.HttpConnector"
minProcessors
="3"
maxProcessors
="20"
acceptCount
="10"
/>
- The
acceptCount
attribute sets the number of requests that can be queued waiting to be handled. - The
minProcessors
attribute sets the number of request processors that are created when the servlet container starts up. - The
maxProcessors
attribute sets the total number of request processors or that can be used to handle requests.
- Q1.In How many ways we can develop a servlet?
- Q2.What is the difference between CGI & Servlet?
- Q3.What is the difference between traditional & Fast CGI?
- Q4.What is the difference between ServletConfig & ServletContext?
- Q5.How to define a Servlet?
- Q6.Specify parallel technologies to the servlet?
- Q7.What is the difference between web server & web container?
- Q8.What is the difference between web server & application server?
- Q9.What are the various types of web containers?
- Q10.By using which 2 Packages we can implement Servlet?
- Q11.What is the purpose of RequestDispatcher?
- Q12.What methods we can call on RequesrDispatcher Object?
- Q13.Explain about SingleThreadModeal?
- Q14.Explain about SingleThreadModeal?
- Q15.What are the various methods present in SingleThreadModeal?
- Q16.What is the marker interface? Example?
- Q17.By using which interfaces we can implements Filter concept?
- Q18.What are the various listeners are available in Servlet specification?
- Q19.What are the various Event classes present in Servlet Specification?
- Q20.By using which object we can send text data as response from the Servlet?
- Q21.By using which object we can read binary data send by the client?
- Q22.By using which object we can send binary data send as response from the Servlet?
- Q23.What are the (various ) lifecycle methods of the Servlet?
- Q24.Explain the purpose of the init() method & How many times it will be excuted? When it will be executed?
- Q25.If init() method throws any Exception i.e; if init() method fails to execute then what will be happen?
- Q26.Is it possible to write constructor with in the Servlet?
- Q27.Why init() is required to perform initialization activities instead of constructor?
- Q28.Is it possible to perform Initialization activities with in the constructor?
- Q29.What is the purpose of service() & How Many times it will be Executed?
- Q30.Explain about destroy?
- Q31.Is it Possible to call destroy() method explicitly from service?
- Q32. With in the <servlet-mapping> how many url pattrerns taken at a time?
- Q33.Explain LifeCycle of the Servlet?
- Q34.What is the purpose of <load-on-startup>?
- Q35.What is the significance of the number for <load-on-startup>?
- Q36.If two servlets having same <load-on-startup>value then which wii be loaded first?
- Q37.Explain about GenericServlet?
- Q38.Which interfaces are implemented by GenericServlet?
- Q39.What is the necessity of having 2 init() methods with in the Servlet?
- Q40.Explain best way of overriding init()?
- Q41.What are various possible status code of response?
- Q42.Explain the difference between GET&POST?
- Q43.What are various HttpRequest methods?
- Q44.What is the difference between HEAD&GET?
- Q45.What is the difference between PUT&GPOST?
- Q46.Which Http methods are non-idempotent?
- Q47.Which Http methods are idempotent?
- Q48.In how many ways we can trigger a GET request?
- Q49.What is the default method for the form?
- Q50.What are different ways to trigger POST request?
- Q51.How many service() methods available in HttpServlet?
- Q52.Explain life cycle of getRequest?
- Q53.Is it recommended to override service() in Http based Servlet?
- Q54.If you are sending Get request but our Servlet contains doGet() & service() Methods then which method will be executed?
- Q55.If you are sending Get request but our Servlet doesn't contain doGet() what happen?
- Q56.Even though HttpServlet doesn't contain any abstract method why it is declared as abstract class?
- Q57.What are the various methods to retrieve from parameters?
- Q58.What is the purpose of request Headers?
- Q59.How we can retrieve headers associated with the ServletRequest?
- Q60. To what value is a variable of the String type automatically initialized?How we can retrieve cookies from the request?
- Q61.By using which method we can get client &server information from the request?
- Q62.How we can add response headers to the ServletResponse?
- Q63.How we can set ContentType to the response?
- Q64.What is the MIME type?
- Q65.Is it possible to send multiple content type as response from the same servlet?
- Q66.Write Servlet code to send movie file as response?
- Q67.Is it possible to get PrintWriter & ServletOutputStream objects simultaneously?
- Q68.How we can implement Redirection mechanism?
- Q69.Explain, difference between sendRedirect&forword?
- Q70.How many times we can call sendRedirect() method with in the same Servlet?
- Q71.How we can add cookies to the response?
- Q72.Explain the directory structure of a web application?
- Q73.In which location we have to place static content?
- Q74.Is it possible to access resources present in the context root directly?
- Q75.Is WEB-INF folder mandatory for web application?
- Q76.Explain about web.xml?
- Q77.Where we have to place 3rd party jar files?
- Q78.If the required class file available in classes folder and lib folder jar file, then which one will get preference?
- Q79.Is there any alternate location to place servlet .class file Other than classes folder?
- Q80.Is it possible to access web.xml directory?
- Q81.Where we have to place tag libraries inside web application?
- Q82.Is it important the order of tags in the web.xml?
- Q83.Can you specify any 10 tags of web.xml?
- Q84.With in the <web-app> which tags are mandatory?
- Q85.What is the purpose of <servlet-name>
- Q86.How many names are possible for a servlet in web-app?
- Q87.Is it possible to configure jsp's in web.xml?
- Q88.When we have to configure jsp's in web.xml?
- Q89.What is the purpose of Servlet initialization parameters and explain how to configure in web.xml?
- Q90.With in the servlet how we can access logical name of the servlet?
- Q91.With in the servlet how we can access Servlet initialization parameter?
- Q92.What is the ServletConfig object and explain the methods available in ServletConfig interface?
- Q93.What is the purpose of <load-on-startup>explain its advantages & disadvantages?
- Q94.If two Servlets having same<load-on-startup> values what will be happen?
- Q95.How many types of url patterns are possible according to Servlet specification?
- Q96.With in the <servlet-mapping>how many url pattrern tags we can take?
- Q97.How to configure defult Servlet in web.xml and when it will get chance for execution?
- Q98.What is the difference between url, uri & urn?
- Q99.How we can get Contextpath and quereyString directly with in the Servlet?
- Q100.What is the necessity of welcome-file and explain How to configure welcome files in web.xml?
- Q101.What is the default welcome-file?
- Q102. Is it possible to configure welcome file in folder wise?
- Q103.What is the necessity of error page and explain the process of Configuration in web.xml?
- Q104.How to send ErrorCode programmatically?
- Q105.What is the purpose of <mime-mapping>?
- Q106.Explain about of war file & the process of creation?
- Q107.What is the purpose of META-INF folder?
- Q108.Explain about MANIFEST.MF?
- Q109.Explain about <context-param>tag & <init-param>?
- Q110.What are the differences between Servlet initialization parameters& Context initialization parameters?
- Q111.How we can access context parameters and servlet parameters with in the Servlet?
- Q112.How we can declare context & Servlet <init-parameters>in web.xml?
- Q113.What is the scope of <context-param>&<init-param>?
- Q114.What are the difference between parameters & attributes?classhierarchy?
- Q115.What is the purpose of an attribute?
- Q116.What are various scopes available for Servlets?
- Q117.Explain the cases where we should go for each scope?
- Q118.explain the methods to perform following activities?
- a) Adding an attribute?
- b) Get the name of an attribute?
- c) Remove an attribute?
- d) Modify the value of an attribute?
- e) To display all attribute names present in a specified scope?
- Q119.If we store information in application scope by default it is available everywhere with in the web application, then what is the need of session and Request scopes?
- Q120.What is the purpose of RequestDispatcher?
- Q121.How many possible ways we can get the RequestDispatcher?
- Q122.What is the difference between obtaining RequestDispatcher from ServletRequest and ServletContext object?
- Q123.What is the difference between forward() &include()?
- Q124.What is the difference between forward() &sendRedirect()?
- Q125.What is the foreign RequestDispatcher & explain the process how we can get it?
- Q126.What are various attributes added by web container while forwarding & including? What is the purpose of these attributes?
- Q127.What is the purpose of filter? Explain the cases where exactly required?
- Q128.By using which interfaces we can implement filter concepts?
- Q129. What is the purpose of FilterChain?
- Q130.How we can configure filter in web.xml?
- Q131.In how many ways we can map a filter?
- Q132.What is the purpose of <dispatcher> tag?
- Q133.What are the default values of <dispatcher> tag?
- Q134.What are allowed values of <dispatcher> tag?
- Q135.In filter chain in which order the filters will be executed?
- Q136.What is the difference between Filter interface doFilter() & FilterChain doFilter()?
- Q137.What is the intercepting filter design pattern?
- Q138.What is the purpose of wrapper?
- Q139.Explain the types of wrappers?
- Q140.Explain Decorator design pattern?
- Q141.Explain the cases where you used filters & wrappers in your previous project?
- Q142.What is the need of Session Management? Explain cases where Session Management is required with example?
- Q143.What are the various Session Management techniques are available?
- Q144.Explain the process of creating Session object?
- Q145.What is the difference between getSession() & getSession(boolean b)?
- Q146.Explain with an example where getSession(false) is required?
- Q147.How we can invalidate a Session?
- Q148.Define Session management?
- Q149.How we can configure SessionTimeout in web.xml?
- Q150.What is the difference between <Session-timeout>and <SetMaxInactiveInterval>?
- Q151.How to know SessionCreation time & lastaccesed time?
- Q152.Explain the Session Management Mechanism by SessionAPI?
- Q153.What is the default session timeout?
- Q154.Explain Session Management by using Cookies?
- Q155.How the SessionId is exchanging between Client & Server?
- Q156.What is the difference between Session API & Cookie which approach is recommended?
- Q157.What is the difference between persistent and non persistent cookies?
- Q158.What is URL Rewriting?
- Q159.By using which Methods we can implement URLRewriting?
- Q160.BY using which methods we can identify under laying Session Management technique?
- Q161.Explain advantages & disadvantages of
- cookies
- URL Writing
- Session API
- Q162.Explain the purpose of Listener?
- Q163.What are the various listeners are available according to Servlet specification?
- Q164.What is the difference between ServletRequestListener and ServletRequestAttributeListener?
- Q165.How to configure listener in web.xml?
- Q166.To print hit count of the web application which listener is required to use?
- Q167.To print the no of active session objects at server side which listener is responsible?
- Q168.What is the difference between HSAL & HSBL?
- Q169.What are various methods present in binding listeners?
- Q170.Explain about HttpSessionActivationListener?
- Q171.At the time of application deployment to perform certain activities which listener is responsible?
- Q172.What are various listeners which are not required to configure in web.xml?
- Q173.What are various event classes available in ServletSpecification?
- Q174.Is it possible to configure more than one listener of same type?
- Q175.If you are configures more than one listener of the same type then in which order listener will be executed?
- Q176.Who is responsible to perform instantiation of listener?
- Q177.At what time listener classes will be instantiated?
- Q178.What is the difference between declarative Security & programmatic security?
- Q179.By using which methods we can implement programmatic Security?
- Q180.What is the purpose of <security-role-ref>?
- Q181.How we can configure users in Tomcat?
- Q182.In your previous project how you implement security?
- Q183.In your previous project what type of authentication used?
- The