spice.util.Chained.scala Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of spice-core_3 Show documentation
Show all versions of spice-core_3 Show documentation
Core functionality leveraged and shared by most other sub-projects of YouI.
package spice.util
import cats.effect.IO
import java.util.concurrent.atomic.AtomicBoolean
import scala.concurrent.duration._
/**
* Provides a single-chain of tasks so only one IO can run at a time blocking the others until it completes.
*
* @param delay the time to sleep between checks to get a lock
*/
case class Chained(delay: FiniteDuration = 100.millis) {
private val active = new AtomicBoolean(false)
private def lock(): IO[Unit] = IO(active.compareAndSet(false, true)).flatMap {
case true => IO.unit
case false => IO.sleep(delay).flatMap(_ => lock())
}
private def unlock(): IO[Unit] = IO(active.set(false))
def apply[Return](effect: IO[Return]): IO[Return] = lock().flatMap { _ =>
effect.guarantee(unlock())
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy