Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added Reference trait.

  • Loading branch information...
commit ef94ef0787d3d58921bbc8c6ef952326ec9a1e7e 1 parent 925120f
david@mel authored
1  build.local.properties
View
@@ -0,0 +1 @@
+scala.home=/usr/local/scala
18 src/scalax/control/concurrent.scala
View
@@ -16,13 +16,29 @@ import scala.collection.jcl.MapWrapper
import java.util.concurrent.atomic._
import java.util.concurrent.{ConcurrentHashMap => JConcurrentHashMap, _}
-final class AtomicCell[A](init : A) {
+final class AtomicCell[A](init : A) extends Reference[A] {
private val ref = new AtomicReference(init)
def compareAndSet(expect : A, update : A) : Boolean =
ref.compareAndSet(expect, update)
def get : A = ref.get().asInstanceOf[A]
def getAndSet(n : A) : A = ref.getAndSet(n).asInstanceOf[A]
def set(n : A) : Unit = ref.set(n)
+
+ final override def modify(f : A => A) {
+ val oldValue = get;
+
+ if (!compareAndSet(oldValue, f(oldValue))) modify(f);
+ else ();
+ }
+
+ final override def modifyWith[S](f : A => (A, S)) : S = {
+ val oldValue = get;
+ val (newValue, s) = f(oldValue);
+
+ if (!compareAndSet(oldValue, newValue)) modifyWith(f);
+ else s;
+ }
+
override def toString() : String = ref.get.toString
def weakCompareAndSet(expect : A, update : A) : Boolean =
ref.weakCompareAndSet(expect, update)
38 src/scalax/control/reference.scala
View
@@ -0,0 +1,38 @@
+package scalax.control;
+
+trait Reference[T]{
+ def get : T;
+ def set(t : T) : Unit;
+
+ def apply() = get;
+ def update(t : T) = set(t);
+
+ def modify(f : T => T) = set(f(get));
+
+ def modifyWith[S](f : T => (T, S)) : S = {
+ val (t, s) = f(get);
+ set(t);
+ s;
+ }
+
+ def preserving[S](action : =>S) : S = {
+ val oldT = get;
+
+ try { action }
+ finally { set(oldT); }
+ }
+
+ def withValue[S](t : T)(action : => S) = preserving{
+ set(t);
+ action;
+ }
+}
+
+class Ref[T](private[this] var value : T) extends Reference[T]{
+ def get = value;
+ def set(t : T) = value = t;
+}
+
+object Ref{
+ def apply[T](t : T) = new Ref(t);
+}
33 tests/scalax/control/reference.scala
View
@@ -0,0 +1,33 @@
+import scalax.control._
+import scalax.testing._
+
+object RefTests extends TestSuite("Ref"){
+ "initial value" is {
+ val ref = Ref(1);
+ assertEq(ref(), 1);
+ }
+
+ "set" is {
+ val ref = Ref(1);
+ ref() = 2;
+ assertEq(ref(), 2);
+ }
+
+ "withValue" is {
+ val ref = Ref(1);
+
+ ref.withValue(3){
+ assertEq(ref(), 3)
+ }
+
+ assertEq(ref(), 1);
+ }
+
+ "modify" is {
+ val ref = Ref(1);
+
+ ref.modify(_+1);
+
+ assertEq(ref(), 2);
+ }
+}
4 tests/scalax/main.scala
View
@@ -15,6 +15,10 @@ import scalax.testing._
object ScalaxTests extends TestSuite("Scalax") {
include(CommandLineTests)
include(CsvTests)
+
+ // scalax.control
+
+ include(RefTests)
// scalax.io
include(StreamHelpTests)
Please sign in to comment.
Something went wrong with that request. Please try again.