Skip to content

Commit

Permalink
Don't hold lock while sorting (#317)
Browse files Browse the repository at this point in the history
* Don't hold lock while sorting

* Fix up types
  • Loading branch information
garrettmoon authored Oct 26, 2022
1 parent bbffd7f commit 97a5dbd
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions Source/PINMemoryCache.m
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,10 @@ - (void)removeObjectAndExecuteBlocksForKey:(NSString *)key
PINCacheObjectBlock didRemoveObjectBlock = _didRemoveObjectBlock;
[self unlock];

if (object == nil) {
return;
}

if (willRemoveObjectBlock)
willRemoveObjectBlock(self, key, object);

Expand Down Expand Up @@ -239,13 +243,18 @@ - (void)trimToCostLimit:(NSUInteger)limit

[self lock];
totalCost = _totalCost;
NSArray *keysSortedByCost = [_costs keysSortedByValueUsingSelector:@selector(compare:)];
[self unlock];

if (totalCost <= limit) {
return;
}

[self lock];
NSDictionary *costs = [_costs copy];
[self unlock];

NSArray *keysSortedByCost = [costs keysSortedByValueUsingSelector:@selector(compare:)];

for (NSString *key in [keysSortedByCost reverseObjectEnumerator]) { // costliest objects first
[self removeObjectAndExecuteBlocksForKey:key];

Expand All @@ -272,9 +281,11 @@ - (void)trimToCostLimitByDate:(NSUInteger)limit
return;

[self lock];
NSArray *keysSortedByAccessDate = [_accessDates keysSortedByValueUsingSelector:@selector(compare:)];
NSDictionary *accessDates = [_accessDates copy];
[self unlock];

NSArray *keysSortedByAccessDate = [accessDates keysSortedByValueUsingSelector:@selector(compare:)];

for (NSString *key in keysSortedByAccessDate) { // oldest objects first
[self removeObjectAndExecuteBlocksForKey:key];

Expand Down

0 comments on commit 97a5dbd

Please sign in to comment.