diff --git a/includes/bootstrap.inc b/includes/bootstrap.inc
index 0b81dc0..0e6227f 100644
--- a/includes/bootstrap.inc
+++ b/includes/bootstrap.inc
@@ -901,23 +901,29 @@ function drupal_get_filename($type, $name, $filename = NULL) {
  * configuration file.
  */
 function variable_initialize($conf = array()) {
-  // NOTE: caching the variables improves performance by 20% when serving
-  // cached pages.
-  if ($cached = cache_get('variables', 'cache_bootstrap')) {
-    $variables = $cached->data;
-  }
-  else {
-    // Cache miss. Avoid a stampede.
-    $name = 'variable_init';
-    if (!lock_acquire($name, 1)) {
-      // Another request is building the variable cache.
-      // Wait, then re-run this function.
-      lock_wait($name);
-      return variable_initialize($conf);
+  $retry_limit = isset($conf['variable_initialize_retry_limit']) ? $conf['variable_initialize_retry_limit'] : 5;
+
+  $name = 'variable_init';
+  $tries = 0;
+  $lock_acquired = FALSE;
+  do {
+    $tries++;
+    if ($cache = cache_get('variables', 'cache_bootstrap')) {
+      $variables = $cache->data;
     }
     else {
-      // Proceed with variable rebuild.
-      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
+      $lock_acquired = lock_acquire($name);
+      if (!$lock_acquired) {
+        lock_wait($name, 1);
+      }
+    }
+  }
+  while (!$cache && !$lock_acquired && ($tries < $retry_limit));
+
+  if (!$cache) {
+    $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
+    // Only write the cache back if we succeeded in acquiring the lock.
+    if ($lock_acquired) {
       cache_set('variables', $variables, 'cache_bootstrap');
       lock_release($name);
     }
