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

Scala example source code file (ConcurrentTest.scala)

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

Learn more about this Scala project at its project page.

Java - Scala tags/keywords

concurrenttest, countdownlatch, failed, long, prop, should, speclite, string, threading, threads, unit, withtimeout

The ConcurrentTest.scala Scala example source code

package scalaz
package concurrent

import java.util.concurrent._
import org.scalacheck.Prop

object ConcurrentTest extends SpecLite{

  "Current test tools" should {
    "succeed on exhaused CountDownLatch" in {
      val latch = new CountDownLatch(1)
      latch.countDown
      assertCountDown(latch, "Should always be processed immediately")
    }

    "run forked code" in {
      val latch = new CountDownLatch(1)
      fork {
        latch.countDown
      }
      assertCountDown(latch, "Should be processed asynchronously")
    }

    "run test with timeout" in {
      (withTimeout(2000) {
        true
      })
    }

    "fail when timeout occurs" in {
      (withTimeout(100) {
        Thread.sleep(2000)
        ()
      }).mustThrowA[RuntimeException]
    }
  }

  def assertCountDown(latch: CountDownLatch, hint: String, timeout: Long = 1000) : Prop = {
    if (latch.await(timeout, TimeUnit.MILLISECONDS)) ()
    else sys.error("Failed to count down within " + timeout + " millis: " + hint)
  }

  def fork(f: => Unit) {
    new Thread {
      override def run() {
        f
      }
    }.start()
  }

  final class WithTimeout(timeout: Long) {
    def apply[A](test: => A): A = {
      val latch = new CountDownLatch(1)
      @volatile var result: A = null.asInstanceOf[A]
      fork {
        result = test
        latch.countDown
      }
      if (latch.await(timeout, TimeUnit.MILLISECONDS)) result
      else sys.error("Timeout occured, possible deadlock.")
    }
  }

  def withTimeout(timeout: Long) = new WithTimeout(timeout)
}

Other Scala examples (source code examples)

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