aspose file tools*
The moose likes Threads and Synchronization and the fly likes Threads servicing JMS messages and use of timer/sleep Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Threads servicing JMS messages and use of timer/sleep" Watch "Threads servicing JMS messages and use of timer/sleep" New topic
Author

Threads servicing JMS messages and use of timer/sleep

Les Hartzman
Ranch Hand

Joined: Sep 19, 2012
Posts: 31
I've got threads from a newFixedThreadPool that submist a thread class that implements MessageListener. I need to also have this thread wake up every 5 seconds to check the current state of an object. Is there a better way other than using "sleep(5000)" in run() within a forever loop?

Thanks.

Les
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18997
    
  40

Les Hartzman wrote:I've got threads from a newFixedThreadPool that submist a thread class that implements MessageListener. I need to also have this thread wake up every 5 seconds to check the current state of an object. Is there a better way other than using "sleep(5000)" in run() within a forever loop?


Another option is to use newScheduledThreadPool() instead -- and to have the task run every five seconds. It is almost the same, except since it is the scheduler that does the potential sleep, it may do other tasks instead. Of course, your task has to be coded to only do one iteration -- no forever loop.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Les Hartzman
Ranch Hand

Joined: Sep 19, 2012
Posts: 31
Thanks for the response. The problem is that the thread is also handling asynchronous JMS messages so changing it to only check messages on a periodic basis would be an issue.

Les
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18909
    
    8

Do the two tasks absolutely have to be done by one thread? Because it looks easier to have two threads doing the two different things, and cooperating... somehow.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Threads servicing JMS messages and use of timer/sleep