- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Arrays with volatile elements
Hi
I have an array that is being acted on simultaneously by several
threads. I need the entries in the array to be volatile (so updates
in one cache get propagated to other caches). Is the correct way to
declare the array as follows?
val x = new Array[Double @volatile](N)
How would this differ from the following?
@volatile var x = new Array[Double](N)
Best wishes
Gavin










Re: Arrays with volatile elements
What you want isn't directly achievable given the design of the JVM. Fortunately it doesn't need to be: All this would achieve in JVM land is a happens before guarantee on reads and writes, which is easy to achieve.
You could write something like the following:
class VolatileDoubleArray(val length : Int){
val array = new Array[Double](length);
@volatile var marker = 0;
def apply(i : Int) = {marker; array(i); }
def update(i : Int, x : Double) { array(i) = x; marker = 0; }
}
Every write to the array happens-before a write to the volatile marker variable and every read from the array happens-after a read from the volatile marker. This should give you the ordering guarantees you want.
Re: Arrays with volatile elements
On Tue, Dec 30, 2008 at 12:05 PM, David MacIver <david [dot] maciver [at] gmail [dot] com> wrote:
Slick.
--
Lift, the simply functional web framework http://liftweb.net
Collaborative Task Management http://much4.us
Follow me: http://twitter.com/dpp
Git some: http://github.com/dpp
Re: Arrays with volatile elements
Java 1.5 and up have Atomic*Array in java.util.concurrent.atomic . With them you can use either "compareAndSet" to get CAS semantics, or just use "set" to get volatile semantics. Unfortunately, there doesn't seem to be an AtomicDoubleArray, which is a bit surprising since deep in the bowels of the beast it should be the same thing as AtomicLongArray.
See http://java.sun.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html for details.
On Sat, Dec 27, 2008 at 4:51 AM, Gavin Lowe <gavin [dot] lowe [at] comlab [dot] ox [dot] ac [dot] uk> wrote:
Re: Arrays with volatile elements
Does the jvm spec allow for such a thing?