Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Servlet object confusion

Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Confused about difference between threads, servlet instance.

When I type on the browser and try to hit the servlet. The servlets constructor is run then initialized, then the service method runs. After it runs it will then run its destroy method right?

My confusion is, how can then multiple threads run the same servlet object if it is destroyed after it completes its run method.
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
servlet's once instantiated will be there for-ever in your container.(I mean until u stop sever /server crashes/explicitly u remove servlet from container)
destroy method will be called only when server is going down (that is its a call back method).
By default only one instance of servlet exist in your container (unless u specifically tell the container i dont want single instance by implementing SingleThread Model).
Hope this helps.

Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The destroy() method will only be called when the application, or the server, is stopped or restarted. When a browser sends a request to a servlet, the container does not actually invoke the service() method directly, but rather creates and starts a Thread whose run() method invokes the service() method of the servlet instance in memory (always the same one, unless, confusingly, the SingleThreadModel interface is implemented by the servlet).

This way, it does not matter how many clients access the servlet at once, the container can just keep creating more threads (within reason).
I don't always make ads but when I do they're tiny
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic