All Downloads are FREE. Search and download functionalities are using the official Maven repository.

spice.util.Chained.scala Maven / Gradle / Ivy

There is a newer version: 0.7.2
Show newest version
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