Last active
March 11, 2019 10:55
-
-
Save reevik/3f7d331b60c5946681159ed9db9c85ae to your computer and use it in GitHub Desktop.
This file contains 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
package io.ryos.demos.fibers; | |
import static java.lang.System.out; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.concurrent.SynchronousQueue; | |
public class FiberDemo { | |
public static void main(String[] args) { | |
// sync queue without any capacity. | |
SynchronousQueue<Integer> syncQueue = new SynchronousQueue<>(); | |
// schedule a producer fiber to create numbers from 1 to n. | |
Fiber.schedule(() -> { | |
int counter = 0; | |
while (true) { | |
++counter; | |
var ct = Thread.currentThread(); | |
out.println(String.format("Putting the value: %d, Thread: %s", counter, ct.getName())); | |
syncQueue.put(counter); // blocks | |
} | |
}); | |
out.println("Scheduled the producer fiber... - " + Thread.currentThread().getName()); | |
takeWhile(syncQueue, 5); | |
out.println("Scheduled the consumer fiber... - " + Thread.currentThread().getName()); | |
} | |
private static List<Integer> takeWhile(final SynchronousQueue<Integer> syncQueue, final int n) { | |
// schedule another fiber, which consumes n integers. | |
final Fiber<List<Integer>> fiber = Fiber.schedule(() -> { | |
List<Integer> result = new ArrayList<>(); | |
for (var i = 0; i < n + 1; i++) { | |
var take = syncQueue.take(); // blocks | |
var ct = Thread.currentThread(); | |
out.println(String.format("Reading the value: %d, Thread: %s", take, ct.getName())); | |
result.add(take); | |
} | |
return result; | |
}); | |
return fiber.join(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment