Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ public BoundedBlockingQueue(int capacity) {

}

public void put(T item) {
public void put(T item) throws InterruptedException {

}

public T take() {
public T take() throws InterruptedException {
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,12 @@ public void attachMonitor(StreamingMonitor monitor) {
public void run() {
// Writer threads are intentionally infinite for the task contract.
while (true) {
if (!monitor.acquire(this)) {
return;
}
output.print(message);
onTick.run();
monitor.release(this);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,46 @@
package hse.java.lectures.lecture6.tasks.synchronizer;

import java.util.List;

public class StreamingMonitor {
// impl your sync here

private final List<StreamWriter> writers;
private final int totalTicks;
private int nextIndex = 0;
private int ticks = 0;

public StreamingMonitor(List<StreamWriter> writers, int ticksPerWriter) {
this.writers = writers.stream()
.sorted((a, b) -> Integer.compare(a.getId(), b.getId()))
.toList();
this.totalTicks = writers.size() * ticksPerWriter;
}

public synchronized boolean acquire(StreamWriter writer) {
while (ticks < totalTicks && writers.get(nextIndex) != writer) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
return ticks < totalTicks;
}

public synchronized void release(StreamWriter writer) {
++ticks;
nextIndex = (nextIndex + 1) % writers.size();
notifyAll();
}

public synchronized void awaitCompletion() {
while (ticks < totalTicks) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,19 @@ public Synchronizer(List<StreamWriter> tasks, int ticksPerWriter) {
* in strict ascending id order.
*/
public void execute() {
// add monitor and sync
StreamingMonitor monitor = new StreamingMonitor(tasks, ticksPerWriter);

for (StreamWriter writer : tasks) {
writer.attachMonitor(monitor);
}

for (StreamWriter writer : tasks) {
Thread worker = new Thread(writer, "stream-writer-" + writer.getId());
worker.setDaemon(true);
worker.start();
}

monitor.awaitCompletion();
}

}
Loading