Created
October 5, 2023 02:44
-
-
Save rokon12/cc4b8026780d351e1c55e7a4166ba3e3 to your computer and use it in GitHub Desktop.
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
package ca.bazlur.concurrency101; | |
import java.util.Random; | |
import java.util.concurrent.CyclicBarrier; | |
import java.util.concurrent.TimeUnit; | |
import java.util.stream.IntStream; | |
public class CyclicBarrierDemo { | |
public static void main(String[] args) throws InterruptedException { | |
final int numberOfPortfolios = 3; | |
Runnable barrierAction = () | |
-> System.out.println("All portfolios have completed the current step. " + | |
"Proceeding to the next step."); | |
var barrier = new CyclicBarrier(numberOfPortfolios, barrierAction); | |
var random = new Random(); | |
IntStream.rangeClosed(1, numberOfPortfolios) | |
.forEach(i -> Thread.startVirtualThread( | |
new PortfolioTask(("Portfolio " + i), | |
barrier, random.nextLong(1000)))); | |
TimeUnit.SECONDS.sleep(30); | |
System.out.println("Hope by now all work is done!"); | |
} | |
} | |
record PortfolioTask(String portfolioName, | |
CyclicBarrier barrier, | |
Long sleepTime) implements Runnable { | |
@Override | |
public void run() { | |
try { | |
System.out.println(portfolioName + " is gathering data..."); | |
TimeUnit.MILLISECONDS.sleep(sleepTime); | |
barrier.await(); | |
System.out.println(portfolioName + " is calculating risk..."); | |
TimeUnit.MILLISECONDS.sleep(sleepTime); | |
barrier.await(); | |
System.out.println(portfolioName + " is generating the report..."); | |
TimeUnit.MILLISECONDS.sleep(sleepTime); | |
barrier.await(); | |
System.out.println(portfolioName + " risk assessment is complete."); | |
} catch (Exception e) { | |
Thread.currentThread().interrupt(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment