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

Scala example source code file (sync-var.scala)

This example Scala source code file (sync-var.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, array, atomicinteger, atomicinteger, test, test, thread, thread, threading, threads

The Scala sync-var.scala source code

import java.util.concurrent._
import java.util.concurrent.atomic._

object Test { def main(args: Array[String]) {

val n = 10000
val i = new AtomicInteger(n)
val j = new AtomicInteger(n)
val sum = new AtomicInteger

val q = new scala.concurrent.SyncVar[Int]

val producers = (1 to 3) map { z => new Thread {
  override def run() {
    var again = true
    while (again) {
      val x = i.getAndDecrement()
      if (x > 0)
        q put x
      else
        again = false
    }
  }
} }

val summers = (1 to 7) map { z => new Thread {
  override def run() {
    val x = j.decrementAndGet()
    if (x >= 0) {
      sum addAndGet q.take()
    }
    if (x > 0) {
      run()
    } else {
      // done
    }
  }
} }

summers foreach { _.start() }
producers foreach { _.start() }

summers foreach { _.join() }

val got = sum.get
val expected = (n + 1) * n / 2
println(got + " " + expected + " " + (got == expected))

producers foreach { _.join() }

} }

// vim: set ts=2 sw=2 et:

Other Scala examples (source code examples)

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

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

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 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.