diff --git a/src/phpbrowscap/Browscap.php b/src/phpbrowscap/Browscap.php
index <HASH>..<HASH> 100644
--- a/src/phpbrowscap/Browscap.php
+++ b/src/phpbrowscap/Browscap.php
@@ -617,9 +617,23 @@ class Browscap
 
         // Get the whole PHP code
         $cache = $this->_buildCache();
+        $dir   = dirname($cache_path);
 
-        // Save and return
-        return (bool) file_put_contents($cache_path, $cache, LOCK_EX);
+        // "tempnam" did not work with VFSStream for tests
+        $tmpFile = $dir . '/temp_' . md5(time() . basename($cache_path));
+
+        if (false === file_put_contents($tmpFile, $cache)) {
+            // writing to the temparary file failed
+            return false;
+        }
+
+        if (false === rename($tmpFile, $cache_path)) {
+            // renaming file failed, remove temp file
+            @unlink($tmpFile);
+            return false;
+        }
+
+        return true;
     }
 
     /**
@@ -1070,7 +1084,7 @@ class Browscap
                     curl_setopt($ch, CURLOPT_USERAGENT, $this->_getUserAgent());
 
                     $file = curl_exec($ch);
-    
+
                     curl_close($ch);
 
                     if ($file !== false) {
write to a temporary file and rename it laster