Fix null check in Cache.

Change-Id: I0e5924889c82fe47ea8e7e318b9a7694dc6afa61
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/189421
Reviewed-by: Brian Wilkerson <brianwilkerson@google.com>
Commit-Queue: Konstantin Shcheglov <scheglov@google.com>
diff --git a/pkg/analyzer/lib/src/dart/analysis/cache.dart b/pkg/analyzer/lib/src/dart/analysis/cache.dart
index 5f50eb1..ca97db6 100644
--- a/pkg/analyzer/lib/src/dart/analysis/cache.dart
+++ b/pkg/analyzer/lib/src/dart/analysis/cache.dart
@@ -38,17 +38,18 @@
   }
 
   void _evict() {
-    while (_currentSizeBytes > _maxSizeBytes) {
-      if (_map.isEmpty) {
-        // Should be impossible, since _currentSizeBytes should always match
-        // _map.  But recover anyway.
-        assert(false);
-        _currentSizeBytes = 0;
-        break;
+    if (_currentSizeBytes > _maxSizeBytes) {
+      var keysToRemove = <K>[];
+      for (var entry in _map.entries) {
+        keysToRemove.add(entry.key);
+        _currentSizeBytes -= _meter(entry.value);
+        if (_currentSizeBytes <= _maxSizeBytes) {
+          break;
+        }
       }
-      K key = _map.keys.first;
-      V value = _map.remove(key)!;
-      _currentSizeBytes -= _meter(value);
+      for (var key in keysToRemove) {
+        _map.remove(key);
+      }
     }
   }
 }