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

Scala example source code file (Atomic.scala)

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

atomic, atomicreference, atomics

The Atomic.scala Scala example source code

package scalaz
package concurrent

import effect._

import java.util.concurrent.atomic.AtomicReference

trait Atomic[A] {
  def compareAndSet(expected: A, newValue: A): IO[Boolean]
  def get: IO[A]
  def getAndSet(a: A): IO[A]
  def set(a: => A): IO[Unit]

  def update(f: A => A): IO[A] = get flatMap { a =>
    val b = f(a)
    compareAndSet(a, b) flatMap { s =>
      if (s) IO(b)
      else update(f)
    }
  }
}

object Atomic extends Atomics

trait Atomics {
  def newAtomic[A](a: A): IO[Atomic[A]] = IO(new Atomic[A] {
    val value = new AtomicReference(a)

    def compareAndSet(expected: A, newValue: A) = IO(value.compareAndSet(expected, newValue))
    def get = IO(value.get)
    def getAndSet(a: A) = IO(value.getAndSet(a))
    def set(a: => A) = IO(value.set(a))
  })
}

Other Scala examples (source code examples)

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