Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Are there scenarios where polling for events would be better than using the observer pattern? I have a fear of using polling and would only start using it if someone gave me a good scenario. All I can think of is how the observer pattern is better than polling. Conside this scenario:

You are programming a car simulator. The car is an object. As soon as the car turns on, you want to play a "vroom vroom" sound clip.

You can model this in two ways:

Polling: Poll the car object every second to see if it's on. When it's on, play the sound clip.

Observer pattern: Make the car the Subject of the observer pattern. Have it publish the "on" event to all observers when itself turns on. Create a new sound object that listens to the car. Have it implement the "on" callback, which plays the sound clip.

In this case, I think the observer pattern wins. Firstly, polling is more processor intensive. Secondly, the sound clip does not immediately fire when the car turns on. There can be up to a 1 second gap because of the polling period.

share|improve this question
    
I can think of almost no scenario. Observer pattern is what actually maps to real world and real life. Thus I think no scenario would ever justify not using it. –  Saeed Neamati Aug 22 '11 at 7:43
    
Are you talking about user interface events, or events in general? –  Bryan Oakley Aug 22 '11 at 11:17
1  
Your example doesn't remove the polling/observing problem. You've simply passed it to a lower level. Your program still needs to figure out if the car is on or not by some mechanism. –  Dunk Aug 22 '11 at 15:29

5 Answers 5

up vote 23 down vote accepted

Imagine you want to get notified about every engine cycle, e.g. to display an RPM measurement to the driver.

Observer pattern: The engine publishes an "engine cycle" event to all observers for each cycle. Create a listener that counts events and updates the RPM display.

Polling: The RPM display asks the engine at regular intervals for an engine cycle counter, and updates the RPM display accordingly.

In this case, the observer pattern would probably loose: the engine cycle is a high-frequency, high-priority process, you don't want to delay or stall that process just to update a display. You also don't want to thrash the thread pool with engine cycle events.


PS: I also use the polling pattern frequently in distributed programming:

Observer pattern: Process A sends a message to process B that says "each time an event E occurs, send a message to Process A".

Polling pattern: Process A regularly sends a message to process B that says "if you event E occured since the last time I've polled, send me a message now".

The polling pattern produces a bit more network load. But the observer pattern has downsides, too:

  • If process A crashes, it will never unsubscribe, and process B will try to send notifications to it for all eternity, unless it can reliably detect remote process failures (not an easy thing to do)
  • If event E is very frequent and/or the notifications carry a lot of data, then process A might get more event notifications than it can handle. With the polling pattern, it can just throttle the polling.
  • In the observer pattern, high load can cause "ripples" through the whole system. If you use blocking sockets, these ripples can go both ways.
share|improve this answer
1  
Good point. Sometimes it's better too poll for the sake of performance. –  Falcon Aug 22 '11 at 8:12
    
Expected number of observers is also a consideration. When you expect a large number of observers, updating them all from the observed can become a performance bottleneck. Much easier to then just write a value somewhere and have the "observers" check that value when they need it. –  Marjan Venema Aug 22 '11 at 8:25
1  
"unless it can reliably detect remote process failures (not an easy thing to do)" ... except by polling ;P. Thus the best design there is to minimise the "nothing has changed" response as much as possible. +1, good answer. –  pdr Aug 22 '11 at 9:24
    
I think the observer pattern for the engine RPM example can be fixed. You can publish only each 100th event with if (count % 100 == 0) to reduce excessive processing. –  JoJo Aug 22 '11 at 17:29
1  
@Jojo: You could, yes, but then you are putting policy that should belong in the display into the RPM counter. Perhaps the user occasionally wants to have a highly precise RPM display. –  Zan Lynx Aug 22 '11 at 18:56

Polling has some disadvantages, you basically stated them already in your question.

However, it can be a better solution, when you want to truly decouple the observable from any observers. But sometimes it might be better to use an observable wrapper for the object to be observed in such cases.

I'd only use polling when the observable can't be observed with object interactions, which is frequently the case when querying databases for example, where you can't have callbacks. Another issue might be multithreading, where it's often times safer to poll and process messages rather than invoking objects directly, to avoid concurrency issues.

share|improve this answer

Polling is better if the polling process runs considerably slower than the things it polls. If you are writing events to a database, it's often better to poll all your event producers, collect all the events that have occurred since the last poll, then write them in a single transaction. If you tried to write every event as it occurred, you might not be able to keep up and eventually would have problems when your input queues filled up. It also makes more sense in loosely-coupled distributed systems, where latency is high or connection set-up and tear-down are expensive. I find polling systems easier to write and understand, but in most situations observers or event-driven consumers seem to offer better performance (in my experience).

share|improve this answer

Polling is a lot easier to get to work over a network when connections may fail, servers may go done etc. Remember at the end of the day a TCP socket needs “polling” keep-a-live messages otherwise the server will assume the client has gone away.

Polling is also good when you wish to keep a UI updated, but the underlying objects change very fast, there is no point update the UI more than a few times a second in most apps.

Provided the server can response “no change” at very low cost and you don’t poll too often and you don’t have 1000s of clients polling, then polling works very well in real life.

However for “in memory” cases, I default to using the observer pattern as it is normally the least work.

share|improve this answer

For a good example of when polling takes over from notification, look at operating system networking stacks.

It was a big deal for Linux when the networking stack enabled NAPI, a networking API that allowed the drivers to switch from an interrupt mode (notification) to a polling mode.

With multiple gigabit Ethernet interfaces the interrupts would often overload the CPU, causing the system to run slower than it ought to. With polling the network cards collect packets in buffers until polled or the cards even write the packets into memory via DMA. Then when the operating system is ready it polls the card for all of its data and does the standard TCP/IP processing.

The polling mode allows the CPU to collect Ethernet data at its maximum processing rate without useless interrupt load. The interrupt mode allows the CPU to idle between packets when work is not so busy.

The secret is when to switch from one mode to the other. Each mode has advantages and should be used in the proper place.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.