Computer Science Canada

Waiting for messages in a message queue

Author:  Martin [ 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.

Author:  rizzix [ Tue Jan 31, 2006 9:01 pm ]
Post 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.

Author:  Martin [ Tue Jan 31, 2006 9:20 pm ]
Post subject: 

Hey, good idea. Smile I'll try that when I get home. Thanks.


: