Question

What is both faster and "better practice", using a polling system or a event based timer?

I'm currently having a discussion with a more senior coworker regarding how to implement some mission critical logic. Here is the situation:

  • A message giving an execution time is received.
  • When that execution time is reached, some logic must be executed.
  • Now multiple messages can be received giving different execution times, and the logic must be executed each time.

I think that the best way to implement the logic would be to create a timer that would trigger the logic when the message at the time in the message, but my coworker believes that I would be better off polling a list of the messages to see if the execution time has been reached.

His argument is that the polling system is safer as it is less complicated and thus less likely to be screwed up by the programmer. My argument is that by implementing it my way, we reduce the reduce the computational load and thus are more likely execute the logic when we actually want it to execute. How should I implement it and why?


Requested Information

  • The only time my logic would ever be utilized would almost certainly be at a time of the highest load.
  • The requirements do not specify how reliable the connection will be but everyone I've talked to has stated that they have never heard of a message being dropped
  • The scheduling is based on an absolute system. So, the message will have a execution time specifying when an algorithm should be executed. Since there is time synchronization, I have been instructed to assume that the time will be uniform among all machines.
  • The algorithm that gets executed uses some inputs which initially are volatile but soon stabilize. By postponing the processing, I hope to use the most stable information available.
Was it helpful?

Solution

The java.util.Timer effectively does what your colleague suggests (truth be told, in the end, there really aren't that many ways to do this).

It maintains a collection of TimerTasks, and it waits for new activity on it, or until the time has come to execute the next task. It doesn't poll the collection, it "knows" that the next task will fire in N seconds, and waits until that happens or anything else (such as a TimerTask added or deleted). This is better overall than polling, since it spends most of its time sleeping.

So, in the end, you're both right -- you should use a Timer for this, because it basically does what your coworker wants to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top