Skip to content

Instantly share code, notes, and snippets.

@vlad17
Created December 1, 2016 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlad17/bdeddc9b240e7975040f34f6dea23533 to your computer and use it in GitHub Desktop.
Save vlad17/bdeddc9b240e7975040f34f6dea23533 to your computer and use it in GitHub Desktop.
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