How to implement an array of volatile elements

I am trying to port a Java application to Scala. One part of the Java application has an implementation called AtomicDoubleBufferthat uses AtomicLongArrayunder the hood - using the result Double.longBitsToDouble(value)to read from a double buffer and Double.doubleToRawLongBits(value)write to the buffer.

I am browsing the net for a Scala implementation that could be better, and I landed on this , which says that this code block

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; }
}

should give me an opportunity - before guarantees. But I'm a little confused as much as possible. Why does a volatile marker on one variable determine that the previous non-volatile “operation” succeeds? My interpretation of JSL 17.4.5 suggests that updating elements arrayin one thread does not guarantee that other threads will see this update. Am I missing something? Or am I confusing everything that happens before?

+4
source share
1 answer

This implementation in your example is correct and does earlier than it guarantees.

Becuse write to volatile variable , , , , .

"" .

: "

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; }
}

"

update, volatile marker=0;, apply volatile marker;.

( ) ( , update , apply, ).

+1

Source: https://habr.com/ru/post/1657499/


All Articles