Skip to content

Instantly share code, notes, and snippets.

@vlad17 vlad17/Average.java
Created Dec 1, 2016

Embed
What would you like to do?
Wait-free Universal Construction
public class Average implements Sequential<Double, Integer> {
private long count = 0;
private long sum = 0;
private Average() {}
public static class AverageFactory implements Factory<Average> {
public Average generate() { return new Average(); }
}
public Double apply(Integer x) {
sum += x;
count += 1;
return 1.0 * sum / count;
}
}
public class AverageDemo {
public static void main(String... args) {
Universal<Double, Integer> universal =
new SlowUniversal<Double, Integer>(
new Average.AverageFactory());
for (int i = 0; i < 10; i++) {
int ii = i;
(new Thread() {
public void run() {
for (int j = 0; j < 10; j++) {
System.out.println(Thread.currentThread() + " " + j + ": " + universal.apply(ii * 10 + j));
}
}
}).start();
}
}
}
public interface Factory<T> { T generate(); } // generate new default object
public interface Sequential<R, I>
{
// Apply an invocation (method + arguments)
// and get a response (return value + state)
R apply(I i);
}
import java.util.concurrent.*;
public class SlowUniversal<R, I> implements Universal<R, I> {
private Factory<? extends Sequential<R, I>> generator;
private ConcurrentLinkedQueue<I> wfq = new ConcurrentLinkedQueue<>();
public SlowUniversal(Factory<? extends Sequential<R, I>> g) { generator = g; }
public R apply(I i) {
wfq.add(i);
Sequential<R, I> s = generator.generate();
for (I invoc : wfq) {
R r = s.apply(invoc);
if (invoc == i) {
// assume references are unique
// we can work around this if we wanted to re-use invocations but there's
// no need to in this example
return r;
}
}
return null;
}
}
public interface Universal<R, I> extends Sequential<R, I> {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.