0

I have a cumbersome object which has to work in background , I create a servlet which will call this object and for running the object I've implemented the Runnable interface inside my servlet like following :

public class myObject extends HttpServlet implements Runnable 
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
        res.print("<br/> running...");
                res.flush(); //doens't help
Thread t = new Thread(this);
                t.run();


}
public void run() 
    {
        res.print("<br/> running...");
                res.flush();//doesn't helper either
        cumbersomeObject.workHard();
    }
}

How can I print this simple line and then send 200 status to user and my servlet work in background happily ever after?

Vahid Hashemi
  • 5,182
  • 10
  • 58
  • 88

2 Answers2

1

Change t.run() to t.start(), your thread is not running in background, but blocking in foreground. BTW how does this compile? How can run() access res variable?

However it looks like you are trying to send some data to a user via res response object from a thread. This won't work, see HttpServletResponse seems to periodically send prematurely for a detailed discussion.

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • res = servletResponse which I've define it as a global varaible and above code is just a snippet ;) – Vahid Hashemi Mar 10 '12 at 23:04
  • @austinpowers: OMG, you can't do this! Single servlet instance is reused for by multiple incoming connections (sort-of singleton), your program will blow-up once it handles more than one clients at a time. – Tomasz Nurkiewicz Mar 10 '12 at 23:07
1

You're making a fundamental mistake. The HTTP servlet request and response objects are tied to the current HTTP request thread. Once this thread finishes (i.e. when the HTTP request/response finished), then the associated HTTP servlet request and response objects are trashed and completely useless. So if you use those objects in a different thread after the initial HTTP request/response finishes, then you'll get exceptions in all colors because they point nowhere to.

Manually spawning new thread on a per-request basis is also a terribly bad idea. Threads are not cheap and definitely not unlimited available. Rather use a pool of 5~10 threads or something. If you have such a thread pool, then you could just submit a task to it, associate it with some unique key in the HTTP session or maybe even in a database along the logged-in user ID. You can then just poll in every subsequent request if the task is finished or not (i.e. it has stored the result there where you'd expect to see it).

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555