souravm wrote: > > This servlet, in its init() method, spawns a thread which opens a socket > connection and listens for any non-HTTP request (or a protocol > independent request). >
Servlets don't necessarily exist between HTTP requests. They can be moved from machine to machine, or serialized out to disk, or be completely destroyed. To the client it looks like the servlet is always running, but that might be an illusion. The servlet container is the magician responsible for hiding all the details, and making sure that the servlet (and all the session and context data) is recreated at the right place in time to handle the next request. The servlet can be notified of these state changes through lifecycle event callbacks. So, if you start a server thread in init(), you can shut it down in destroy().[1] But what happens if the container takes your servlet out of service for 2 hours? If no new requests come in, then your servlet isn't going to be running, and neither will your server thread. If you ignore destroy() events and just leave your server thread running, then you've got a resource leak. What happens if the servlet has moved to a new machine? The init() method is called when it's restarted, do you now how two server threads running? So it's a bad idea to start server threads from servlets. Servlets are for handling HTTP requests and responses.[2] This is why you aren't supposed to start threads from EJB's: it's a big mess. But if you really feel the need to do this sort of thing, and if you're absolutely sure that your servlet container won't be doing any advanced resource management tricks, and you're willing to live with the potential problems, then try: http://www.distributopia.com/servlet_stuff/background_threads.txt Good luck. [1] Well, sometimes you can shut down the thread, but if it's doing anything interesting, maybe you can't. See the URL above. [2] Servlets, at least right now, are just for HTTP. In theory, you could extend servlet containers to manage other protocols, with other lifecycles. That would be the "right" way to have a servlet be an FTP or mail server, for example. People talk about that sort of thing on the list all the time, (see the archives) but it never seems to catch on. I suspect it's a "right tool for the job" problem. Servlets are hammers, HTTP requests are nails. FTP requests are screws. Or something :-) --- Christopher St. John [EMAIL PROTECTED] DistribuTopia http://www.distributopia.com ___________________________________________________________________________ To unsubscribe, send email to [EMAIL PROTECTED] and include in the body of the message "signoff SERVLET-INTEREST". Archives: http://archives.java.sun.com/archives/servlet-interest.html Resources: http://java.sun.com/products/servlet/external-resources.html LISTSERV Help: http://www.lsoft.com/manuals/user/user.html
