Skip to content

Instantly share code, notes, and snippets.

@rokon12
Created October 5, 2023 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rokon12/cc4b8026780d351e1c55e7a4166ba3e3 to your computer and use it in GitHub Desktop.
Save rokon12/cc4b8026780d351e1c55e7a4166ba3e3 to your computer and use it in GitHub Desktop.
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