Created
October 28, 2018 22:39
-
-
Save relgames/723056a13b33a4b965ca1d1f254d6b8d to your computer and use it in GitHub Desktop.
yield in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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