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

Is scalacache thread-safe? #376

Open
soloman817 opened this issue Apr 14, 2020 · 0 comments
Open

Is scalacache thread-safe? #376

soloman817 opened this issue Apr 14, 2020 · 0 comments

Comments

@soloman817
Copy link

I am using CaffeineCache for local in-memory cache, and I want to achieve this:

  • TTL is 10 seconds
  • To get a new value, it is a long process, say cost 5 seconds
  • Provide a REST service, to retrieve the value, if it is older than 10 seconds, I just want to trigger the refreshing of the new value, but I don't want to wait for the new value, in the mean time, I want to just return the old value instead
  • Once the new value is retrieved, I should update the old value

So roughly it is like code here:

    import scalacache._
    import scalacache.caffeine._
    import scalacache.memoization._

    implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.global
    val l1Cache: Cache[Future[Cat]] = CaffeineCache[Future[Cat]]
    val l2Cache: Cache[Cat] = CaffeineCache[Cat]
    val flags: Flags = Flags.defaultFlags

    def getCat(id: Int) = {
      // to trigger refreshing if necessary
      val l1CacheResult: Future[Cat] = memoizeSync[Future[Cat]](Some(10 seconds)){
        Future {
          Thread.sleep(5000)
          val newCat = Cat(id, s"cat $id", s"${Timestamp.now()}")
          // update l2Cache
          put(id)(newCat)(l2Cache, modes.scalaFuture.mode, flags)
          newCat
        }
      }(l1Cache, modes.sync.mode, flags)

      // get the result from l2Cache
      val l2CacheResult: Try[Option[Cat]] = get(id)(l2Cache, modes.try_.mode, flags)

      l2CacheResult.toString
    }

    while (true) {
      println(s"  ${Timestamp.now()} ${getCat(1)}")
      Thread.sleep(1000)
    }
  }

The point is in the l1Cache future, when the new value is retrieved, I want update the l2Cache, that would be in a background thread, but I read them from another thread, would that be thread-safe?

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

No branches or pull requests

1 participant