Take a look at java.langThread.setDaemon() method, may it's what you need
This would be a very bad idea. You'd cause a 100% CPU load without a good reason.
The correct solution is probably to block the thread when the queue is empty. This is trivially implemented with a BlockingQueue
.
SUMMARY:
- Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
- This method must be called before the thread is started.
- This method first calls the checkAccess method of this thread
with no arguments. This may result in throwing a SecurityException (in the
current thread).
SUMMARY: In many cases, what we really want is to create background threads that do simple, periodic tasks in an application. The setDaemon() method can be used to mark a Thread as a daemon thread that should be killed and discarded when no other application threads remain. Normally, the Java interpreter continues to run until all threads have completed. But when daemon threads are the only threads still alive, the interpreter will exit.
Can't I have a thread which is always running? When the app is removed,
that thread is stopped by the corresponding event in my ServletContextListener.
"That thread is stopped"? How? There is no termination condition in your while(true) {...} loop. How are you stopping it? Are you using the Thread.stop() method? That is unsafe and was deprecated way back in Java 1.1
If you use setDaemon(true), the thread will stay active after you have stopped the web-app using your app-server's management tools. Then if you restart the web-app, you'll get another thread. Even if you attempt to undeploy the web-app, the thread will stay running and will prevent the entire web-app from being garbage-collected. Then redeploying the next version will give you an additional copy of everything in memory.
If you provide an exit condition for the loop (e.g. InterruptedException or a volatile "stopNow" boolean), you can avoid this issue.
Your code does not start a new thread, it runs the loop in the same thread and this is why you are getting a timeout error when deployed.
To start a thread you must call the start method, not the run method.
public void contextInitialized(ServletContextEvent sce) {
//Some init code not relevant, omitted for clarity
BidPushThread t= new BidPushThread();
t.setServletContext(sce.getServletContext());
t.start();// run();
}