Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion core-tests/shared/src/test/scala/zio/RefSpec.scala
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package zio

import zio.test.Assertion._
import zio.test.TestAspect._
import zio.test._

import scala.ref.WeakReference

object RefSpec extends ZIOBaseSpec {

def spec = suite("RefSpec")(
Expand Down Expand Up @@ -243,7 +246,27 @@ object RefSpec extends ZIOBaseSpec {
val result = typeCheck(""" Ref.make("").incrementAndGet """)
val expected = "value incrementAndGet is not a member of zio.UIO[zio.Ref[String]]"
assertZIO(result)(isLeft(startsWithString(expected)))
}
},
test("Initial value is GC'd") {
class Bar
ZIO.succeedUnsafe { implicit u =>
val n = 1000
var i = 0
val refs = Array.ofDim[Ref.Atomic[Bar]](n)
val weakRefs = Array.ofDim[WeakReference[Bar]](n)
while (i < n) {
val bar = new Bar()
val ref = Ref.unsafe.make(bar)
refs(i) = ref
weakRefs(i) = new WeakReference[Bar](bar)
ref.unsafe.set(null)
i += 1
}
java.lang.System.gc()

assertTrue(!weakRefs.exists(_.get.nonEmpty))
}
} @@ jvmOnly
)
)

Expand Down
9 changes: 7 additions & 2 deletions core/shared/src/main/scala/zio/Ref.scala
Original file line number Diff line number Diff line change
Expand Up @@ -374,8 +374,10 @@ object Ref extends Serializable {
def updateSomeAndGet(pf: PartialFunction[A, A])(implicit unsafe: Unsafe): A
}

val unsafe: UnsafeAPI =
new AtomicReference[A](initial) with UnsafeAPI { ref: AtomicReference[A] =>
val unsafe: UnsafeAPI = {
// NOTE: Instantiate the AtomicReference with a null and then set its value
// so that the initial value is not added as a class field allowing it to be GC'd
val ref0 = new AtomicReference[A]() with UnsafeAPI { ref: AtomicReference[A] =>
def get(implicit unsafe: Unsafe): A =
ref.asInstanceOf[AtomicReference[A]].get

Expand Down Expand Up @@ -436,6 +438,9 @@ object Ref extends Serializable {
.asInstanceOf[AtomicReference[A]]
.updateAndGet((current: A) => pf.applyOrElse(current, (_: Any) => current))
}
ref0.asInstanceOf[AtomicReference[A]].set(initial)
ref0
}

@deprecated("Kept for binary compatibility only. Do not use", "2.1.15")
private[zio] def value: AtomicReference[A] = unsafe.asInstanceOf[AtomicReference[A]]
Expand Down
Loading