Synchronization By Sleeping

AntiPattern Name: Synchronization by sleeping

Type: Design

Problem: The need to synchronize with some external event, especially in a concurrent or multithreaded program, and there isn't any easy way to absolutely determine if the event has occurred.

Context: Concurrent designs.

Forces: Need for synchronization/rendevous; lack of facilities to provide it.

Supposed Solution: Use sleep() or similar function to cause the task desiring synchronize to wait for a "sufficiently long time", after which it is believed the desired event will have occurred.

Resulting Context: Two things, neither good:

1. Bad: Often times, you will wait far longer than necessary, in an effort to avoid the second result below--reducing overall performance of the system.

2. Worse: Sometimes, you won't wait long enough; and the still hasn't occurred when the timer expires. Death and destruction results.

Often times, the amount of time to wait is determined empirically--one time value is tried, and if it produces failures due to #2 above, a longer time constant is tried, until the system stabilizes. Eventually, a failure occurs in a deployed system, and a TurdFanCollision occurs.

In some cases, you are lucky and there is a maximal bound on the time needed. In most cases, the time for the event to occur is unbound (though the time may follow a Pareto or similar distribution, and be bounded within a reasonable range the vast majority of the time, leading to a false sense of security that a maximal bound was indeed chosen).

This AntiPattern is popular because it's easy to implement. Since it works most of the time, it will pass UnitTests most of the time (and if it doesn't, run them again!)

Refactored Solution:

If you have control over the subsystem you are waiting for, modify it to notify the world that it is done by a suitable mechanism. If you have a way of polling it to see if it is done, do that. (A polling loop with a sleep() in the middle is an acceptable though not ideal solution).

In some cases, though, you may not be able to either a) modify the system so that it signals completion or b) detect completion from outside. In that case you should design your software such that is tolerant of this fault occurring.

Design Rationale:

Related AntiPatterns:

Applicable Positive Patterns:

AntiPatternCategory:

Also Known As:


Examples in the Literature:


Examples in Practice:


EditText of this page (last edited July 28, 2004) or FindPage with title or text search