Skip to content

Commit

Permalink
add apply method for Mapref
Browse files Browse the repository at this point in the history
  • Loading branch information
Yisrael Union committed Sep 17, 2024
1 parent eb231ff commit a327788
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 39 deletions.
36 changes: 1 addition & 35 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions std/shared/src/main/scala/cats/effect/std/MapRef.scala
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,22 @@ trait MapRef[F[_], K, V] extends Function1[K, Ref[F, V]] {

object MapRef extends MapRefCompanionPlatform {

/**
* the default Constructor for MapRef.
* If Async is available, it will use a ConcurrentHashMap, otherwise it will use a sharded immutable map.
*/
def apply[F[_]: Concurrent, K, V](): F[MapRef[F, K, Option[V]]] = {

Concurrent[F] match {
case a: Async[_] =>
implicit val async: Async[F] = a
ofConcurrentHashMap()
case _ =>
ofShardedImmutableMap[F, K, V](Runtime.getRuntime.availableProcessors())
}

}

/**
* Creates a sharded map ref to reduce atomic contention on the Map, given an efficient and
* equally distributed hash, the contention should allow for interaction like a general
Expand Down
17 changes: 13 additions & 4 deletions tests/shared/src/test/scala/cats/effect/std/MapRefSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,27 @@

package cats.effect.std

import cats._
import cats.*
import cats.data.State
import cats.effect._
import cats.implicits._
import cats.effect.*
import cats.effect.unsafe.implicits.global
import cats.implicits.*

import scala.concurrent.duration._
import java.util.concurrent.ConcurrentHashMap
import scala.concurrent.duration.*

class MapRefSpec extends BaseSpec {
private val smallDelay: IO[Unit] = IO.sleep(20.millis)
private def awaitEqual[A: Eq](t: IO[A], success: A): IO[Unit] =
t.flatMap(a => if (Eq[A].eqv(a, success)) IO.unit else smallDelay *> awaitEqual(t, success))

"MapRef[Async]()" should {
"be instance of ConcurrentHashMap" in real {
val mapRef = MapRef[IO,Int, Int]().unsafeRunSync()
mapRef.isInstanceOf[ConcurrentHashMap[ Int, Int]] must_=== true

}
}
"MapRef.ofSingleImmutableMapRef" should {

"concurrent modifications" in real {
Expand Down

0 comments on commit a327788

Please sign in to comment.