Skip to content

Instantly share code, notes, and snippets.

@RChehowski
Created June 6, 2019 11:57
Show Gist options
  • Save RChehowski/1e26d190d4ec563b7e121beb99723ffe to your computer and use it in GitHub Desktop.
Save RChehowski/1e26d190d4ec563b7e121beb99723ffe to your computer and use it in GitHub Desktop.
Cyclic barrier download
package com.company;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CyclicBarrier;
public class Main {
static class Task implements Runnable {
private final int executionTimeMs;
Task(int executionTimeMs) {
this.executionTimeMs = executionTimeMs;
}
@Override
public void run() {
try {
System.out.println("I am " + toString());
Thread.sleep(executionTimeMs);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class DownloadTask extends Task {
private final int index;
DownloadTask(int index) {
super((int)(Math.random() * 1000.0));
this.index = index;
}
@Override
public String toString() {
return getClass().getSimpleName() + " " + index;
}
}
private static class InstallTask extends Task {
private final int index;
InstallTask(int index) {
super((int)(Math.random() * 2000.0));
this.index = index;
}
@Override
public String toString() {
return getClass().getSimpleName() + " " + index;
}
}
private static Collection<DownloadTask> downloadTasks = new ArrayList<>();
private static Queue<InstallTask> installTasks = new ConcurrentLinkedQueue<>();
private static CyclicBarrier barrier = new CyclicBarrier(2);
private static void downloadTasksExecutor() {
for (Iterator<DownloadTask> iterator = downloadTasks.iterator(); iterator.hasNext(); ) {
final DownloadTask t = iterator.next();
t.run();
installTasks.add(new InstallTask(t.index));
if (barrier.getNumberWaiting() == 1) {
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
iterator.remove();
}
System.out.println("downloadTasksExecutor finished");
}
private static void installTasksExecutor() {
while (!downloadTasks.isEmpty()) {
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
InstallTask t;
while ((t = installTasks.poll()) != null)
t.run();
}
System.out.println("installTasksExecutor finished");
}
public static void main(String[] args) throws Exception
{
for (int i = 0; i < 10; i++)
downloadTasks.add(new DownloadTask(i));
final Thread downloadThread = new Thread(Main::downloadTasksExecutor);
final Thread installThread = new Thread(Main::installTasksExecutor);
downloadThread.start();
installThread.start();
installThread.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment