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

Scala example source code file (boundedbuffer.scala)

This example Scala source code file (boundedbuffer.scala) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Scala tags/keywords

array, boundedbuffer, get, int, manifest, n, n, put, put, stop, stop, t, t

The Scala boundedbuffer.scala source code

package examples.actors

import scala.actors.Actor._

object boundedbuffer {
  class BoundedBuffer[T](N: Int)(implicit m: Manifest[T]) {
    private case class Put(x: T)
    private case object Get
    private case object Stop

    private val buffer = actor {
      val buf = new Array[T](N)
      var in, out, n = 0
      loop {
        react {
          case Put(x) if n < N =>
            buf(in) = x; in = (in + 1) % N; n += 1; reply()
          case Get if n > 0 =>
            val r = buf(out); out = (out + 1) % N; n -= 1; reply(r)
          case Stop =>
            reply(); exit("stopped")
        }
      }
    }

    def put(x: T) { buffer !? Put(x) }
    def get: T = (buffer !? Get).asInstanceOf[T]
    def stop() { buffer !? Stop }
  }

  def main(args: Array[String]) {
    val buf = new BoundedBuffer[Int](1)
    buf.put(42)
    println("" + buf.get)
    buf.stop()
  }
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala boundedbuffer.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.