Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix race condition in LruCache when handling exceptions #692

Merged
merged 1 commit into from
Jun 17, 2024

Conversation

JD557
Copy link
Member

@JD557 JD557 commented Jun 17, 2024

Reorders the operations in the LruCache to avoid race conditions.

When the future failed, the other threads could still fetch the failed result before the cache entry was deleted (this can be simulated by adding a blocking(Thread.sleep(1000)) between the instructions).

Now the cache entry is deleted first, leaving other threads free to create new futures, before marking the returned future as failed.

This was detected by flaky tests in https://github.com/adzerk/apso/pull/690/checks.

Does this change relate to existing issues or pull requests?

No

Does this change require an update to the documentation?

No

How has this been tested?

Unit tests.

I also reproduced the previous issue by changing the code to:

promise.complete(value)
scala.concurrent.blocking(Thread.sleep(1000))
if (value.isFailure) store.remove(key, promise.future)

Doing the same thing with the new ordering does not cause any issue.

@@ -85,8 +85,7 @@ class ExpiringLruCacheSpec(implicit ee: ExecutionEnv) extends Specification {
cache(2)(Future.successful("B")) must beEqualTo("B").await
cache(3)("C") must beEqualTo("C").await
cache.store.toString === "{1=A, 2=B, 3=C}"
cache(4)("D")
Thread.sleep(10)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I noticed that this test is now a bit more flaky.

I do think that we wanted the await here, not Thread.sleep.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. The await is more appropriate.

@JD557 JD557 requested a review from jcazevedo June 17, 2024 08:59
Copy link
Member

@jcazevedo jcazevedo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! Thanks!

@jcazevedo jcazevedo merged commit d69d684 into master Jun 17, 2024
14 checks passed
@jcazevedo jcazevedo deleted the fix-cache-race-condition branch June 17, 2024 09:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants