Skip to content
Open
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 @@ -28,9 +28,11 @@ public void attachMonitor(StreamingMonitor monitor) {
public void run() {
// Writer threads are intentionally infinite for the task contract.
while (true) {
output.print(message);
onTick.run();
try {
monitor.tick(id, onTick, output, message);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

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

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.With;

import java.io.PrintStream;

@Getter
public class StreamingMonitor {
// impl your sync here
}
private final Object key = new Object();
private final int N;
private final int ticksPerWriter;
private int cnt = 0;
private int nowId = 1;

public StreamingMonitor(int size, int ticksPerWriter) {
this.N = size;
this.ticksPerWriter = size * ticksPerWriter;
}

public synchronized void check() throws InterruptedException {
while(cnt < ticksPerWriter){
wait();
}
}

public synchronized void tick(int idCome, Runnable onTick, PrintStream output, String message) throws InterruptedException {

while (idCome != nowId || cnt >= ticksPerWriter) {
wait();
}

nowId = Integer.max(1, (nowId + 1) % (N+1));
cnt += 1;

output.print(message);
onTick.run();

notifyAll();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package hse.java.lectures.lecture6.tasks.synchronizer;

import javax.management.monitor.Monitor;
import java.util.List;

public class Synchronizer {
Expand All @@ -22,12 +23,25 @@ public Synchronizer(List<StreamWriter> tasks, int ticksPerWriter) {
* in strict ascending id order.
*/
public void execute() {
// add monitor and sync
StreamingMonitor streamingMonitor = new StreamingMonitor(tasks.size(), ticksPerWriter);

for (var stream : tasks){
stream.attachMonitor(streamingMonitor);
}

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

try {
streamingMonitor.check();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}


}

}
}
Loading