hi, i'm a bit confused with thread in servlets. i'm trying to run a background process with a while(true) loop and sleep 2mins each time. The idea is that the thread would retrieve a url (ie stock quotes). Each time a request comes thru on doGet, they would automatically have an updated quote. I also looked at the isPrime example. Is that the proper way of accomplishing this task or should i be taking a different approach?
public class PrimeSearcher extends HttpServlet implements Runnable
// kick off in init
public void getQuotes()
public class extends HttpServlet // kick off the getQuotes thread in init
class getQuotes implements Runnable
Joined: Apr 04, 2009
Hi, looks like this will create a separate quote fetching thread for every servlet instance, and each thread will store its own copy of the quotes, thus duplicating the same information. Instead, consider starting just one quote fetching thread from ServerContextListener contextInitialized, and share the quote data between servlet instances (using ServletContext attributes, database,...).
EDIT: Ignore. I should read my specs more carefully.
I wouldn't try to implement runnable from a servlet.
The servlet lifecycle is controlled by the container an is already called from within a threaded context.
Another approach would be to create a plain old Java object to fetch your stock data.
If you want to go with the treaded continuous loop approach, instanciate that object from a context listener.
Have it update some properties in a context scoped bean.
Then when someone makes a request you can look up the stock data from your context scoped bean.
If you want to get away from threads altogether just check the system time with each request, and update your context scoped bean by fetching the stock data whenever the data is more than n minutes old.
If you do go with the threaded approach, make sure you read up on the daemon property of the Thread object. Otherwise, you could end up having problems stopping, and restarting your application and/or container.
Author and all-around good cowpoke
Joined: Mar 22, 2000
The separate Runnable plain old java object approach has many advantages:
1. you can design and test it entirely outside the servlet environment
2. you can write a management function servlet (PW protected of course) to let you monitor how well it is working - delays, errors, etc
3. the management function servlet could be used to pause/restart the process