Skip to content

Instantly share code, notes, and snippets.

@relgames
Created October 28, 2018 22:50
Show Gist options
  • Select an option

  • Save relgames/a643b097835f854152ede2934ef05504 to your computer and use it in GitHub Desktop.

Select an option

Save relgames/a643b097835f854152ede2934ef05504 to your computer and use it in GitHub Desktop.
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
public class Yield {
public abstract static class Generator<T> {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final BlockingQueue queue = new SynchronousQueue();
public Generator() {
executor.execute(() -> {
try {
generate();
} catch (RuntimeException e) {
put(e);
}
});
executor.shutdown();
}
private void put(Object e) {
try {
queue.put(e);
} catch (InterruptedException ignored) {
}
}
private Object get() {
try {
return queue.take();
} catch (InterruptedException e) {
return null;
}
}
final void yield(T value) {
put(value);
}
public T next() {
Object obj = get();
if (obj instanceof RuntimeException) {
throw (RuntimeException) obj;
}
return (T) obj;
}
protected abstract void generate();
}
public static void main(String[] args) {
Generator<Integer> squares = new Generator<>() {
@Override
protected void generate() {
for (int i = 0; i < 10; i++) {
System.out.println("Generating square of " + i);
yield(i * i);
}
throw new RuntimeException("done");
}
};
while (true) {
System.out.println(squares.next());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment