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

Scala example source code file (computeserver.scala)

This example Scala source code file (computeserver.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

application, channel, computeserver, computeserver, int, int, job, job, syncvar, unit, unit

The Scala computeserver.scala source code

package examples

import concurrent._, concurrent.ops._

class ComputeServer(n: Int) {

  private trait Job {
    type t
    def task: t
    def ret(x: t): Unit
  }

  private val openJobs = new Channel[Job]()

  private def processor(i: Int): Unit = {
    while (true) {
      val job = openJobs.read
      println("read a job")
      job.ret(job.task)
    }
  }

  def future[a](p: => a): () => a = {
    val reply = new SyncVar[a]()
    openJobs.write{
      new Job {
        type t = a
        def task = p
        def ret(x: a) = reply.set(x)
      }
    }
    () => reply.get
  }

  spawn(replicate(0, n) { processor })
}

object computeserver extends Application {

  def kill(delay: Int) = new java.util.Timer().schedule(
    new java.util.TimerTask {
      override def run() = {
        println("[killed]")
        System.exit(0)
      }
    },
    delay) // in milliseconds

  val server = new ComputeServer(1)
  val f = server.future(42)
  println(f())
  kill(10000)
}

Other Scala examples (source code examples)

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