aspose file tools*
The moose likes Servlets and the fly likes How to use Threads in Servlets? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "How to use Threads in Servlets?" Watch "How to use Threads in Servlets?" New topic
Author

How to use Threads in Servlets?

aatish pandya
Greenhorn

Joined: Apr 20, 2011
Posts: 21
I am trying hard to use Threads in Servlet, but since the "Thread java file" is a plain java class file, i am not able to know the interaction of Servlet with the Thread, also i don't know how to update the contents of a web browser when a Thread has completed its task? any help?
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16142
    
  21

Welcome to the JavaRanch, Aatish!

DON'T spawn threads in servlets. It's explicily forbidden by the J2EE standard. There's a reason for that.

Web applications are not like traditional client/server applications. Web applications do not run continuously. A web application receives a request from the client (browser), processes it, returns the results and that's it. Each request/response process is independent and it's only by doing various tricks that we can make it appear that there's a larger continuous process at work.

Because web applications can only respond to requests, they cannot asynchronously push data to the client. Not only is there no process running, the network connection back to the client no longer exists once the response has been processed. A whole new connection has to be established for each request/response.

Servlets don't run in their own threads. Instead, when a request comes in, the appserver removes a thread from a master thread pool and uses it to drive the servlet's service (doGet/doPost) method. Once the service method has returned, the thread is returned to the thread pool. If you make that thread spawn a child thread, the thread now in the thread pool will no longer be just like all the other threads in the thread pool, so any other process that gets assigned that thread will end up with unpredictable results.

To handle true independent threads, therefore, you can't spawn them in request service methods. However, you can spawn them in the init() method of a servlet (this is no longer recommended). Or you can create a ContextListener and have it spawn threads.

Because HTTP cannot send unsolicited data to web clients, however, once the thread wants to notify a client, it cannot push out a notification. Instead, the request handlers must interrogate the thread the next time a request is made. For tracking progress of a long-running operation, usually the client web page is set up to automatically refresh itself. Each refresh request polls the web application server, which can then check the thread status.


Customer surveys are for companies who didn't pay proper attention to begin with.
aatish pandya
Greenhorn

Joined: Apr 20, 2011
Posts: 21
Thank you for your reply! I am surprised that one does not use threads in web applications, but then multi-threading is the main feature of java?

However, if you could help me solve my query without using threads, which as per my knowledge is not possible, it would be fine!

I am trying to make a web-based application as follows-
* It is a Test Engine where the Client is asked a set of questions to Test his knowledge on a particular subject maybe Cricket or java itself!
* Now the problem is I want to set a Timer for say 30 minutes to answer the questions after which the session should get closed with the "Time-up" message and give the Result!
* How will I be able to do this if I am not using Threads?
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12805
    
    5
Now the problem is I want to set a Timer for say 30 minutes to answer the questions after which the session should get closed with the "Time-up" message and give the Result!


One essential difference between desktop applications and servlets is exactly that you can't do that. As Tim said, servlets can only respond to requests.

You have to learn a whole new style of programming to work in the browser/server environment. Lots of pitfalls if you try to cram desktop application architecture into a servlet.

For your online test situation, you would record the start time in a session, on subsequent requests you would determine how much time had passed and choose the response accordingly. You can create a fancy timer with JavaScript, which executes on the browser side, but that is a different subject.

Bill
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42277
    
  64
aatish pandya wrote:I am surprised that one does not use threads in web applications

I wouldn't put it like that. Web apps are by their nature multi-threaded - concurrent requests are handled in multiple threads.

I also wouldn't put it as starkly as Tim does - while JEE may forbid spawning new threads, I see nothing wrong with creating new TimerTask in a servlet container. Those would and should not interact with the servlet thread after creation, though.


Ping & DNS - my free Android networking tools app
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16142
    
  21


DON'T spawn threads in servlets. It's explicily forbidden by the J2EE standard.


That's not the same thing as "Don't spawn threads in webapps".

Actually, spawning threads in servlets is OK, providing that it's not done in one of the servlet's request-handling methods. In otter words, the init() method can spawn threads, but methods like service(), doGet(), doPost() and their relatives must not.

I think aatish is confusing a session with a connection. Connections in HTTP are extremely short-lived. Ideally, only a few seconds. Just long enough to process a request/response cycle. Sessions in J2EE are basically objects that hold the context of a series of request/response cycles so that continuity may be maintained.

I will repeat, however:

HTTP does not support unsolicited data from the server to the client. The only time that a server can send data to a client is in response to a request.

That isn't a Java thing, it's a web thing. You cannot have a thread time out and send a notification to a user because HTTP doesn't permit it. You can time something out and pass back a notification when the user next makes a request, but you can't do anything until a user makes a request. HTTP is reactive, not (gag) "pro"active.
Shailesh Narkhede
Ranch Hand

Joined: Jul 10, 2008
Posts: 368
Hi Atish and all,

This thing can be done by using AJAX (although that was not the exact use of AJAX), you can calcuate time by using javascript function and after 30 minutes show popup as "Time out.." and send ajax request to server in that javascript function and invalidate the session.



Thanks,
Shailesh
aatish pandya
Greenhorn

Joined: Apr 20, 2011
Posts: 21
Thanks Tim and rest!

Its true that using Threads is cumbersome in Servlets because even if we start an instance of a Thread from say Servlet1, we may not be able to get its info in Next servlet. if we are using "form action" and "Press Next button" "HTML" in servlet1 to call servlet2, there is no way we can get the Thread info of Servlet1.

One method which I successfully tried is writing the Thread info to a File and also tracking a boolean value Is Thread Running? in another file to stop this Thread when I want to stop this Thread from, say, servlet4!

But, as Shailesh suggested maybe using javascript might solve the purpose, however I am not familiar with AJAX!
 
Consider Paul's rocket mass heater.
 
subject: How to use Threads in Servlets?