Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save relgames/723056a13b33a4b965ca1d1f254d6b8d to your computer and use it in GitHub Desktop.
yield in Java
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
public class Test {
public abstract static class Generator<T> {
private final BlockingQueue<T> queue = new SynchronousQueue<>();
private final ExecutorService executor = Executors.newSingleThreadExecutor();
public Generator() {
executor.execute(this::generate);
executor.shutdown();
}
final void yield(T value) {
try {
queue.put(value);
} catch (InterruptedException ignored) {
}
}
public T next() {
try {
return queue.take();
} catch (InterruptedException e) {
return null;
}
}
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);
}
}
};
Integer s;
while ((s = squares.next()) != null) {
System.out.println(s);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment