Saturday, 18 November 2017

NoVisibility.java example in Java Concurrency in Practice

I've been going through Java Concurrency in Practice and trying to reproduce the examples as I go through.

I found that when trying to illustrate the no visibility problem in chapter 3 the example in the code didn't work for me so I tweaked it a little bit:

import java.util.Random;
import java.util.concurrent.*;
class NoVisibility {
private boolean ready;
private int number;
private final ExecutorService executor;
private final Random random;
NoVisibility(ExecutorService executor, Random random) {
this.executor = executor;
this.random = random;
}
private class Reader implements Callable<Integer> {
@Override
public Integer call() throws Exception {
while (!ready) {
Thread.yield();
}
return number;
}
}
int go() throws ExecutionException, InterruptedException {
Future<Integer> submission = executor.submit(new Reader());
int randomNumber = random.nextInt();
this.number = randomNumber;
ready = true;
return submission.get() - randomNumber;
}
}
Here is the test:

import org.junit.Test;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.assertj.core.api.Assertions.assertThat;
public class NoVisibilityTest {
private ExecutorService executor = Executors.newSingleThreadExecutor();
@Test
public void go() throws ExecutionException, InterruptedException {
Random random = new Random();
while (true) {
assertThat(new NoVisibility(executor, random).go())
.isEqualTo(0);
}
}
}


Then after running it for some time:

org.junit.ComparisonFailure:
Expected :0
Actual   :-1822446613

\o/

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning...