alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (InterruptReq.scala)

This example Scala source code file (InterruptReq.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Scala source code examples by using tags.

All credit for the original source code belongs to scala-lang.org; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Scala tags/keywords

compiler, continuation, either, failedinterrupt, left, list, nsc, option, r, some, throwable, unit

The InterruptReq.scala Scala example source code

package scala.tools.nsc
package util

/** A class of work items to be used in interrupt requests.
 *  Todo: we should replace the Eithers by Futures or Try's.
 */
abstract class InterruptReq {
  /** The result type of the operation
   */
  type R

  /** The operation to be performed */
  protected val todo: () => R

  type Continuation = Either[R, Throwable] => Unit

  /** The result provided */
  private var result: Option[Either[R, Throwable]] = None

  /** The continuations waiting asynchronously on a provided result */
  private var waiting: List[Continuation] = Nil

  /** To be called from interrupted server to execute demanded task */
  def execute(): Unit = synchronized {
    try {
      result = Some(Left(todo()))
    } catch {
      case t: Throwable => result = Some(Right(t))
    } finally {
      notify()
      for (k <- waiting.reverse) k(result.get)
    }
  }

  /** To be called from interrupting client to get result for interrupt */
  def getResult(): R = synchronized {
    while (result.isEmpty) {
      try {
        wait()
      } catch { case _ : InterruptedException => () }
    }

    result.get match {
      case Left(res) => res
      case Right(t) => throw new FailedInterrupt(t)
    }
  }

  def onComplete(k: Continuation) = synchronized {
    if (result.isDefined)
      k(result.get)
    else
      waiting = k :: waiting
  }
}

class FailedInterrupt(cause: Throwable) extends Exception("Compiler exception during call to 'ask'", cause)

Other Scala source code examples

Here is a short list of links related to this Scala InterruptReq.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.