Packages

p

monix

eval

package eval

Ordering
  1. Alphabetic
Visibility
  1. Public
  2. All

Type Members

  1. abstract class Callback [-T] extends Listener[T] with (Try[T]) ⇒ Unit

    Represents a callback that should be called asynchronously with the result of a computation.

    Represents a callback that should be called asynchronously with the result of a computation. Used by Task to signal the completion of asynchronous computations on runAsync.

    The onSuccess method should be called only once, with the successful result, whereas onError should be called if the result is an error.

  2. sealed abstract class Coeval [+A] extends () ⇒ A with Serializable

    Coeval represents lazy computations that can execute synchronously.

    Coeval represents lazy computations that can execute synchronously.

    Word definition and origin:

    • Having the same age or date of origin; a contemporary; synchronous.
    • From the Latin "coævus": com- ‎("equal") in combination with aevum ‎(aevum, "age").
    • The constructor of Coeval is the dual of an expression that evaluates to an A.

    There are three evaluation strategies:

    • Now or Error: for describing strict values, evaluated immediately
    • Once: expressions evaluated a single time
    • Always: expressions evaluated every time the value is needed

    The Once and Always are both lazy strategies while Now and Error are eager. Once and Always are distinguished from each other only by memoization: once evaluated Once will save the value to be returned immediately if it is needed again. Always will run its computation every time.

    Both Now and Error are represented by the Attempt trait, a sub-type of Coeval that can be used as a replacement for Scala's own Try type.

    Coeval supports stack-safe lazy computation via the .map and .flatMap methods, which use an internal trampoline to avoid stack overflows. Computation done within .map and .flatMap is always done lazily, even when applied to a Now instance.

  3. abstract class MVar [A] extends AnyRef

    A mutable location, that is either empty or contains a value of type A.

    A mutable location, that is either empty or contains a value of type A.

    It has 2 fundamental atomic operations:

    • put which fills the var if empty, or blocks (asynchronously) until the var is empty again
    • take which empties the var if full, returning the contained value, or blocks (asynchronously) otherwise until there is a value to pull

    The MVar is appropriate for building synchronization primitives and performing simple inter-thread communications. If it helps, it's similar with a BlockingQueue(capacity = 1), except that it doesn't block any threads, all waiting being done asynchronously by means of Task.

    Given its asynchronous, non-blocking nature, it can be used on top of Javascript as well.

    Inspired by Control.Concurrent.MVar from Haskell and by scalaz.concurrent.MVar.

  4. sealed abstract class Task [+A] extends Serializable

    Task represents a specification for a possibly lazy or asynchronous computation, which when executed will produce an A as a result, along with possible side-effects.

    Task represents a specification for a possibly lazy or asynchronous computation, which when executed will produce an A as a result, along with possible side-effects.

    Compared with Future from Scala's standard library, Task does not represent a running computation or a value detached from time, as Task does not execute anything when working with its builders or operators and it does not submit any work into any thread-pool, the execution eventually taking place only after runAsync is called and not before that.

    Note that Task is conservative in how it spawns logical threads. Transformations like map and flatMap for example will default to being executed on the logical thread on which the asynchronous computation was started. But one shouldn't make assumptions about how things will end up executed, as ultimately it is the implementation's job to decide on the best execution model. All you are guaranteed is asynchronous execution after executing runAsync.

  5. trait TaskApp extends AnyRef

    Safe App type that runs a Task action.

    Safe App type that runs a Task action.

    Clients should implement run, runl, or runc.

    Also available for Scala.js, but without the ability to take arguments and without the blocking in main.

  6. final class TaskCircuitBreaker extends AnyRef

    The TaskCircuitBreaker is used to provide stability and prevent cascading failures in distributed systems.

    The TaskCircuitBreaker is used to provide stability and prevent cascading failures in distributed systems.

    Purpose

    As an example, we have a web application interacting with a remote third party web service. Let's say the third party has oversold their capacity and their database melts down under load. Assume that the database fails in such a way that it takes a very long time to hand back an error to the third party web service. This in turn makes calls fail after a long period of time. Back to our web application, the users have noticed that their form submissions take much longer seeming to hang. Well the users do what they know to do which is use the refresh button, adding more requests to their already running requests. This eventually causes the failure of the web application due to resource exhaustion. This will affect all users, even those who are not using functionality dependent on this third party web service.

    Introducing circuit breakers on the web service call would cause the requests to begin to fail-fast, letting the user know that something is wrong and that they need not refresh their request. This also confines the failure behavior to only those users that are using functionality dependent on the third party, other users are no longer affected as there is no resource exhaustion. Circuit breakers can also allow savvy developers to mark portions of the site that use the functionality unavailable, or perhaps show some cached content as appropriate while the breaker is open.

    How It Works

    The circuit breaker models a concurrent state machine that can be in any of these 3 states:

    1. Closed: During normal operations or when the TaskCircuitBreaker starts
      • Exceptions increment the failures counter
      • Successes reset the failure count to zero
      • When the failures counter reaches the maxFailures count, the breaker is tripped into Open state
    2. Open: The circuit breaker rejects all tasks with an ExecutionRejectedException
      • all tasks fail fast with ExecutionRejectedException
      • after the configured resetTimeout, the circuit breaker enters a HalfOpen state, allowing one task to go through for testing the connection
    3. HalfOpen: The circuit breaker has already allowed a task to go through, as a reset attempt, in order to test the connection
      • The first task when Open has expired is allowed through without failing fast, just before the circuit breaker is evolved into the HalfOpen state
      • All tasks attempted in HalfOpen fail-fast with an exception just as in Open state
      • If that task attempt succeeds, the breaker is reset back to the Closed state, with the resetTimeout and the failures count also reset to initial values
      • If the first call fails, the breaker is tripped again into the Open state (the resetTimeout is multiplied by the exponential backoff factor)

    Usage

    import monix.eval._
    import scala.concurrent.duration._
    
    val circuitBreaker = TaskCircuitBreaker(
      maxFailures = 5,
      resetTimeout = 10.seconds
    )
    
    //...
    val problematic = Task {
      val nr = util.Random.nextInt()
      if (nr % 2 == 0) nr else
        throw new RuntimeException("dummy")
    }
    
    val task = circuitBreaker.protect(problematic)

    When attempting to close the circuit breaker and resume normal operations, we can also apply an exponential backoff for repeated failed attempts, like so:

    val circuitBreaker = TaskCircuitBreaker(
      maxFailures = 5,
      resetTimeout = 10.seconds,
      exponentialBackoffFactor = 2,
      maxResetTimeout = 10.minutes
    )

    In this sample we attempt to reconnect after 10 seconds, then after 20, 40 and so on, a delay that keeps increasing up to a configurable maximum of 10 minutes.

    Credits

    This Monix data type was inspired by the availability of Akka's Circuit Breaker.

  7. final class TaskSemaphore extends Serializable

    The TaskSemaphore is an asynchronous semaphore implementation that limits the parallelism on task execution.

    The TaskSemaphore is an asynchronous semaphore implementation that limits the parallelism on task execution.

    The following example instantiates a semaphore with a maximum parallelism of 10:

    val semaphore = TaskSemaphore(maxParallelism = 10)
    
    def makeRequest(r: HttpRequest): Task[HttpResponse] = ???
    
    // For such a task no more than 10 requests
    // are allowed to be executed in parallel.
    val task = semaphore.greenLight(makeRequest(???))

Value Members

  1. object Callback extends Serializable
  2. object Coeval extends Serializable
  3. object MVar
  4. object Task extends TaskInstances with Serializable
  5. object TaskCircuitBreaker
  6. object TaskSemaphore extends Serializable

Ungrouped