Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Waiting for messages in a message queue
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Martin




PostPosted: Tue Jan 31, 2006 8:33 pm   Post subject: Waiting for messages in a message queue

So here's what I want to do:

I have a PriorityQueue written up in which Message objects are enqueued. A Message object contains two things - a String message, which is the message to be displayed, and a long executionTime, which is the time that the message will be displayed through a System.out.println(message);

Now, I have this system working in what I think is a horrible way to do it. Right now, a while loop keeps peeking at the front of the PriorityQueue, and when the current system time is past the execution time, the message executes. Trouble is, this eats 50% of the CPU while it's running. It seems to me that there has to be a better way to do this.

I thought about just causing the thread to sleep, but unfortunately messages aren't always inserted in order, so the sleep has the potential to be off.

For example, if I insert Message ("this is message 1", 1000) and Message ("this is message 2", 500) at time 0, the output would be:
this is message 2
this is message 1

So yeah. I'm out of ideas. Anyone?

Thanks in advance.
Sponsor
Sponsor
Sponsor
sponsor
rizzix




PostPosted: Tue Jan 31, 2006 9:01 pm   Post subject: (No subject)

hmm, interesting.

Well, here's one way.. I'm not sure if it's a better way, but it might reduce CPU usage *hint: MVC Smile* :

Create a Timer class, that ticks at regular intervals. At every tick it fires a TimerTickEvent or something. Basically it notifies each event listener (TickEventListener) that a new tick has occured.

You can register a your own event handler that basically looks-up the current tick value.. based on that you send the appropriate messages from your priority queue.

If you want to make it fool-proof, I would suggest that you check if those EventListeners also Runnables! If they are, then run them in a new Thread. This can prevent cpu-intensive operations from hogging up too much time, thus preventing screw-ups.
Martin




PostPosted: Tue Jan 31, 2006 9:20 pm   Post subject: (No subject)

Hey, good idea. Smile I'll try that when I get home. Thanks.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: