2

I'm trying to test whether a double provided through a listener monotonically increases with each call. For this, I'm keeping another double for comparison and update that at the end of the listener lambda:

double lastProgress = 0;

operator.addProgressListener(progress -> {
  assertThat(progress, greaterThanOrEqualTo(lastProgress));
  lastProgress = progress;
});

However, this naturally results in a compilation error (Local variable lastProgress defined in an enclosing scope must be final or effectively final), since lastProgress is being altered.

For long variables, a workaround would be to use a final instance of AtomicLong, and set its value accordingly. For doubles, their value could be mapped to long as described here, resulting in the following code:

AtomicLong lastProgress = new AtomicLong(Double.doubleToLongBits(0));

operator.addProgressListener(progress -> {
  assertThat(progress, greaterThanOrEqualTo(Double.longBitsToDouble(lastProgress.get())));
  lastProgress.set(Double.doubleToLongBits(progress));
});

Even though this works, it's quite inconvenient and not trivial to understand what's going on.

As Java comes with no built-in class like AtomicDouble, is there a convenient way of obtaining a mutuable, final object representing a double?

Community
  • 1
  • 1
Cedric Reichenbach
  • 8,970
  • 6
  • 54
  • 89
  • Why not make your own DoubleWrapper with nothing but a public `double` field? – Travis Jan 28 '17 at 15:35
  • 1
    Have you considered the [`MutableDouble`](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/mutable/MutableDouble.html) that comes with Apache Commons? – Joe C Jan 28 '17 at 15:37
  • 1
    There is [AtomicDouble](https://google.github.io/guava/releases/19.0/api/docs/com/google/common/util/concurrent/AtomicDouble.html) in Guava. – kennytm Jan 28 '17 at 15:47
  • @Travis: Considered, but didn't want to reinvent the wheel. – Cedric Reichenbach Jan 28 '17 at 16:19
  • @JoeC, kennytm: Hmm, those look useful. Maybe their existence can be considered an indicator that there's no useful alternative in the standard library. – Cedric Reichenbach Jan 28 '17 at 16:20

0 Answers0