Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Running a thread in background in servlet

 
Kousik Majumder
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I have a requirement to post an alarm when some event happens.

I want to write a servlet which will be called at the time of application start up and will stay active as long as application runs.
A thread in that servlet will always monitor for that event due to which alarm will be generated.

I am actually trying to avoid to use thread in the servlet which may cause the application to run slow.

Is there any better way to do that.
Please suggest some code.

Thank you,
Kousik
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64692
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What exactly do you expect this thread to do when the event happens?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13058
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, a servlet can start a new Thread to accomplish some task.

However, you must avoid having the servlet request/response Thread slowed down or waiting for some event. That would be contrary to the whole servlet architecture and processing model.

Bill
 
Kousik Majumder
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I just want the servlet to keep active as long as the application runs so that it can generate the alarm(i.e it will check db for a threshold crossing) and act accordingly.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does it need to be a Servlet? What's wrong with a simple Timer & TimerTask?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13058
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just want the servlet to keep active as long as the application runs


Assuming you really mean you want the request to stay open, that is contrary to the entire intent of servlets as any tutorial will tell you.

This type of job is usually accomplished with a servlet which starts the separate Thread (or even separate application) and then provides for monitoring it. BUT with multiple request/response cycles.

1. start job, return page saying job started - possibly with Javascript that can fire off a new request

2. each request looks at the status of the job and reports (NOT waiting)

3. finally a request determines that the job is finished and reports the results.

Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic