Created
November 22, 2016 22:36
-
-
Save dirkgr/e6f6aa346347f6cb7a4c3794bf53ca6d to your computer and use it in GitHub Desktop.
Reference counting in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class CountedReference[T <: AutoCloseable](counted: ReferenceCounted[T]) extends AutoCloseable { | |
counted.inc() | |
override def close() = counted.dec() | |
def get = counted.inner | |
} | |
case class ReferenceCounted[T <: AutoCloseable](inner: T) { | |
private val count = new AtomicInteger(0) | |
def inc(): Unit = count.incrementAndGet() | |
def dec(): Unit = { | |
val newCount = count.decrementAndGet() | |
if(newCount == 0) inner.close() | |
} | |
def getReference = new CountedReference(this) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment