8th Home Work, Practical and Theoretical Questions

This commit is contained in:
2026-06-24 13:50:47 +03:30
parent 9e5c715088
commit 501504c760
6 changed files with 637 additions and 116 deletions
+24 -17
View File
@@ -2,10 +2,7 @@ import java.util.Random;
/**
* Simulates downloading a single chunk of a file.
*
* <p>This class is intentionally provided as a skeleton for students.
* The main multithreading and simulation logic should be completed
* in the run() method.</p>
* Each worker writes only to its own assigned ChunkStatus object.
*/
public class DownloadWorker implements Runnable {
@@ -21,23 +18,33 @@ public class DownloadWorker implements Runnable {
@Override
public void run() {
// TODO: Record the chunk start time in chunkStatus.
double downloaded = 0.0;
// Record the start time for this chunk
chunkStatus.setStartTimeMs(System.currentTimeMillis());
// TODO: Print a message that this chunk has started downloading.
double downloaded = 0.0;
int delayRange = config.getMaxStepDelayMs() - config.getMinStepDelayMs();
double stepRange = config.getMaxStepDownloadMB() - config.getMinStepDownloadMB();
while (downloaded < chunkStatus.getChunkSizeMB()) {
// TODO: Generate a random sleep delay between min and max delay.
// TODO: Sleep for that delay.
// TODO: Generate a random download amount for this step.
// TODO: Increase downloaded, but do not go beyond chunk size.
// TODO: Save the updated downloaded value into chunkStatus.
// TODO: Optionally print step-by-step progress.
// Random delay simulating network latency for this step
int delay = config.getMinStepDelayMs() + (delayRange > 0 ? random.nextInt(delayRange) : 0);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
// Random amount downloaded in this step, capped at remaining size
double step = config.getMinStepDownloadMB() + random.nextDouble() * stepRange;
downloaded = Math.min(downloaded + step, chunkStatus.getChunkSizeMB());
// Write only to this worker's own ChunkStatus (thread-safe by design)
chunkStatus.setDownloadedMB(downloaded);
}
// TODO: Mark the chunk as completed.
// TODO: Record the chunk end time in chunkStatus.
// TODO: Print a message that this chunk has finished downloading.
// Mark completion and record end time
chunkStatus.setEndTimeMs(System.currentTimeMillis());
chunkStatus.setCompleted(true);
}
}
+73 -69
View File
@@ -3,7 +3,7 @@ import java.util.List;
public class Main {
public static void main(String[] args) {
System.out.println("=== Simulated Download Manager ===");
System.out.println("=== Simulated Download Manager ===\n");
// 1. Read config
DownloadConfig config;
@@ -14,94 +14,98 @@ public class Main {
return;
}
System.out.println("File name: " + config.getFileName());
System.out.println("Total size (MB): " + config.getTotalSizeMB());
System.out.println("Chunk count: " + config.getChunkCount());
System.out.println("File name : " + config.getFileName());
System.out.println("Total size : " + config.getTotalSizeMB() + " MB");
System.out.println("Chunks : " + config.getChunkCount());
System.out.println("Step delay : " + config.getMinStepDelayMs()
+ "" + config.getMaxStepDelayMs() + " ms");
System.out.println("Step size : " + config.getMinStepDownloadMB()
+ "" + config.getMaxStepDownloadMB() + " MB");
System.out.println();
// 2. Create chunks
// ── MULTITHREADED RUN ──────────────────────────────────────────────
System.out.println("━━━ Multithreaded Download ━━━");
// 2. Create chunk status objects
List<ChunkStatus> chunks = ChunkUtils.createChunks(
config.getTotalSizeMB(),
config.getChunkCount()
);
config.getTotalSizeMB(), config.getChunkCount());
// 3. Create worker threads
// 3. Create one worker thread per chunk
List<Thread> workerThreads = new ArrayList<>();
for (ChunkStatus chunk : chunks) {
DownloadWorker worker = new DownloadWorker(chunk, config);
Thread workerThread = new Thread(worker, "Worker-" + chunk.getChunkId());
workerThreads.add(workerThread);
// TODO:
// Students may print helpful debug information here,
// for example which chunk is assigned to which worker thread.
Thread t = new Thread(worker, "Worker-" + chunk.getChunkId());
workerThreads.add(t);
}
// 4. Create and start monitor thread
// 4. Create and start the monitor thread before workers so it is
// already polling when the first worker begins
ProgressMonitor monitor = new ProgressMonitor(config, chunks);
Thread monitorThread = new Thread(monitor, "Progress-Monitor");
monitorThread.start();
// TODO:
// Start the monitor thread before starting the workers
// so that progress can be displayed while downloading happens.
//
// Example idea:
// monitorThread.start();
// 5. Start all worker threads
long multiStart = System.currentTimeMillis();
for (Thread t : workerThreads) {
t.start();
}
// 5. Start worker threads
// TODO:
// Start each worker thread in workerThreads.
// Use a loop and call start() on each thread.
// 6. Wait for workers to finish
// TODO:
// Wait for all worker threads to complete by calling join().
// This should be done inside a try-catch block for InterruptedException.
//
// Hint:
// for (Thread thread : workerThreads) {
// thread.join();
// }
// TODO:
// After all workers finish, the monitor thread may also need to stop.
// Depending on how ProgressMonitor is implemented, students may:
// - wait for it to finish on its own, or
// - add a stopping mechanism in ProgressMonitor later.
//
// If your monitor finishes automatically, you may join it here.
// NOTE:
// this final report may show 0 progress because no worker has actually run yet.
// Until students complete the thread start/join TODOs above,
// 6. Wait for every worker to finish before printing the final report
try {
for (Thread t : workerThreads) {
t.join();
}
// Monitor exits on its own once it detects all chunks are done;
// join here to make sure the final "All chunks completed" line is printed
monitorThread.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Main thread interrupted while waiting for workers.");
return;
}
long multiTime = System.currentTimeMillis() - multiStart;
// 7. Print final report
System.out.println();
System.out.println("=== Final Report ===");
int completedChunks = 0;
double downloadedMB = 0.0;
System.out.println("━━━ Final Report ━━━");
int completedCount = 0;
double totalDownloaded = 0.0;
for (ChunkStatus chunk : chunks) {
downloadedMB += chunk.getDownloadedMB();
if (chunk.isCompleted()) {
completedChunks++;
}
System.out.println(
"Chunk " + chunk.getChunkId()
+ ": " + chunk.getDownloadedMB()
+ "/" + chunk.getChunkSizeMB()
+ " MB"
);
totalDownloaded += chunk.getDownloadedMB();
if (chunk.isCompleted()) completedCount++;
System.out.printf(" Chunk #%d : %.1f / %.1f MB (%.2fs)%n",
chunk.getChunkId(),
chunk.getDownloadedMB(),
chunk.getChunkSizeMB(),
chunk.getDownloadDurationMs() / 1000.0);
}
System.out.printf(" Completed : %d / %d chunks%n", completedCount, chunks.size());
System.out.printf(" Downloaded: %.1f / %.1f MB%n",
totalDownloaded, (double) config.getTotalSizeMB());
System.out.printf(" Wall time : %.2f seconds%n%n", multiTime / 1000.0);
// ── SEQUENTIAL RUN (Bonus comparison) ───────────────────────────
System.out.println("━━━ Sequential Download (Bonus Comparison) ━━━");
List<ChunkStatus> seqChunks = ChunkUtils.createChunks(
config.getTotalSizeMB(), config.getChunkCount());
long seqTime = SequentialDownloader.run(config, seqChunks);
// ── COMPARISON REPORT ──────────────────────────────────────────────
System.out.println();
System.out.println("Completed chunks: " + completedChunks + "/" + chunks.size());
System.out.println("Downloaded total: " + downloadedMB + "/" + config.getTotalSizeMB() + " MB");
System.out.println("━━━ Performance Comparison ━━━");
System.out.printf(" Sequential : %.2f seconds%n", seqTime / 1000.0);
System.out.printf(" Multithreaded : %.2f seconds%n", multiTime / 1000.0);
System.out.printf(" Speedup : %.2fx%n", (double) seqTime / Math.max(multiTime, 1));
System.out.println();
System.out.println(" Analysis:");
System.out.println(" In the multithreaded run each worker sleeps independently,");
System.out.println(" so all network-latency delays overlap in parallel.");
System.out.println(" The sequential run must wait for each chunk in turn,");
System.out.println(" making the total time roughly N × (average chunk time).");
System.out.println();
System.out.println("Simulation finished.");
}
}
+154 -30
View File
@@ -1,5 +1,17 @@
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
/**
* Monitors and displays real-time download progress for all chunks.
*
* Bonus features implemented:
* - Real-time in-place progress bar using ANSI escape codes
* - Per-chunk progress bars with completion indicators
* - Overall download speed (MB/s) calculation
* - Estimated Time of Arrival (ETA) calculation
* - Event log showing chunk start/finish events
*/
public class ProgressMonitor implements Runnable {
private final String fileName;
@@ -7,57 +19,87 @@ public class ProgressMonitor implements Runnable {
private final List<ChunkStatus> chunks;
private final long monitorDelayMs;
// Event detection: track previous state to detect chunk start/finish
private final boolean[] wasStarted;
private final boolean[] wasCompleted;
private final Deque<String> eventLog = new ArrayDeque<>();
private static final int MAX_LOG_ENTRIES = 5;
// Speed and ETA tracking
private double previousTotalMB = 0.0;
private long previousTimeMs;
// In-place ANSI update tracking
private int lastPrintedLines = 0;
// ANSI escape codes
private static final String RESET = "\033[0m";
private static final String BOLD = "\033[1m";
private static final String DIM = "\033[2m";
private static final String GREEN = "\033[92m";
private static final String CYAN = "\033[96m";
private static final String YELLOW = "\033[93m";
private static final String CLEAR_LINE = "\033[2K";
private static final int BAR_WIDTH = 30;
public ProgressMonitor(DownloadConfig config, List<ChunkStatus> chunks) {
this.fileName = config.getFileName();
this.totalSizeMB = config.getTotalSizeMB();
this.chunks = chunks;
this.monitorDelayMs = 500;
this.previousTimeMs = System.currentTimeMillis();
this.wasStarted = new boolean[chunks.size()];
this.wasCompleted = new boolean[chunks.size()];
}
@Override
public void run() {
// TODO:
// Repeatedly check chunk progress until all chunks are completed.
// In each loop:
// 1. Read the downloaded size from every chunk
// 2. Add all downloaded amounts to totalDownloadedMB
// 3. Count completed chunks
// 4. Print a progress message
// 5. If completedChunks == chunks.size(), print a final monitor message and stop
// 6. Otherwise sleep for monitorDelayMs and continue
boolean firstPrint = true;
while (true) {
double totalDownloadedMB = 0.0;
int completedChunks = 0;
for (ChunkStatus chunk : chunks) {
// 1. Read progress from every chunk and detect state-change events
for (int i = 0; i < chunks.size(); i++) {
ChunkStatus chunk = chunks.get(i);
totalDownloadedMB += chunk.getDownloadedMB();
if (chunk.isCompleted()) completedChunks++;
if (chunk.isCompleted()) {
completedChunks++;
if (!wasStarted[i] && chunk.getStartTimeMs() > 0) {
wasStarted[i] = true;
addEvent(String.format("Chunk #%d started (%.0f MB)",
chunk.getChunkId(), chunk.getChunkSizeMB()));
}
if (!wasCompleted[i] && chunk.isCompleted()) {
wasCompleted[i] = true;
addEvent(String.format("Chunk #%d finished (%.2fs)",
chunk.getChunkId(), chunk.getDownloadDurationMs() / 1000.0));
}
}
double percent = 0.0;
if (totalSizeMB > 0) {
percent = (totalDownloadedMB * 100.0) / totalSizeMB;
// 2. Calculate speed and ETA
long now = System.currentTimeMillis();
double elapsed = (now - previousTimeMs) / 1000.0;
double speed = elapsed > 0.001 ? (totalDownloadedMB - previousTotalMB) / elapsed : 0.0;
double remaining = totalSizeMB - totalDownloadedMB;
double eta = (speed > 0.01) ? remaining / speed : -1.0;
previousTotalMB = totalDownloadedMB;
previousTimeMs = now;
// 3. Build and print the real-time dashboard
String dashboard = buildDashboard(totalDownloadedMB, completedChunks, speed, eta);
printInPlace(dashboard, firstPrint);
firstPrint = false;
// 5. Exit gracefully once all chunks are done
if (completedChunks == chunks.size()) {
System.out.println(BOLD + GREEN + " All chunks completed! Download finished." + RESET);
break;
}
System.out.printf(
"Progress for %s: %.1f/%.1f MB (%.2f%%), completed chunks: %d/%d%n",
fileName,
totalDownloadedMB,
(double) totalSizeMB,
percent,
completedChunks,
chunks.size()
);
// TODO:
// If all chunks are completed, print a final message and exit the loop
// 6. Sleep before the next polling cycle
try {
Thread.sleep(monitorDelayMs);
} catch (InterruptedException e) {
@@ -66,4 +108,86 @@ public class ProgressMonitor implements Runnable {
}
}
}
private void addEvent(String message) {
if (eventLog.size() >= MAX_LOG_ENTRIES) eventLog.pollFirst();
eventLog.addLast(message);
}
/**
* Overwrites the previous dashboard in-place using ANSI cursor-up sequences,
* producing a smooth real-time update instead of scrolling output.
*/
private void printInPlace(String dashboard, boolean firstPrint) {
if (!firstPrint && lastPrintedLines > 0) {
// Move cursor up to the top of the previous dashboard
System.out.printf("\033[%dA", lastPrintedLines);
}
String[] lines = dashboard.split("\n", -1);
for (String line : lines) {
System.out.print(CLEAR_LINE + line + "\n");
}
System.out.flush();
lastPrintedLines = lines.length;
}
private String buildDashboard(double totalMB, int completedChunks, double speed, double eta) {
StringBuilder sb = new StringBuilder();
String divider = " " + "".repeat(54);
sb.append(BOLD).append(CYAN)
.append(" ┌─ Download Manager ─ ").append(fileName).append("\n")
.append(RESET);
// Per-chunk progress rows
for (ChunkStatus chunk : chunks) {
sb.append(chunkLine(chunk)).append("\n");
}
sb.append(DIM).append(divider).append(RESET).append("\n");
// Overall progress bar
double pct = totalSizeMB > 0 ? totalMB / totalSizeMB * 100.0 : 0.0;
sb.append(String.format(" " + BOLD + "Total " + RESET + " %s %5.1f%% %.1f / %.0f MB\n",
colorBar(pct, BAR_WIDTH), pct, totalMB, (double) totalSizeMB));
// Speed and ETA line
if (speed > 0.01) {
String etaStr = eta >= 0 ? String.format("%.1fs", eta) : "";
sb.append(String.format(" " + YELLOW + "Speed: %.2f MB/s" + RESET
+ " ETA: %-8s chunks: %d / %d\n",
speed, etaStr, completedChunks, chunks.size()));
} else {
sb.append(String.format(" Warming up… chunks: %d / %d\n",
completedChunks, chunks.size()));
}
// Event log
if (!eventLog.isEmpty()) {
sb.append(DIM).append(divider).append(RESET).append("\n");
for (String event : eventLog) {
sb.append(DIM).append(" » ").append(event).append(RESET).append("\n");
}
}
// Remove trailing newline so split gives the right count
String result = sb.toString();
if (result.endsWith("\n")) result = result.substring(0, result.length() - 1);
return result;
}
private String chunkLine(ChunkStatus chunk) {
double pct = chunk.getProgressPercentage();
String tick = chunk.isCompleted() ? GREEN + "" + RESET : " ";
return String.format(" [%s] Chunk #%d %s %5.1f%%",
tick, chunk.getChunkId(), colorBar(pct, BAR_WIDTH), pct);
}
/** Renders a Unicode block-character progress bar with ANSI colour. */
private String colorBar(double percent, int width) {
int filled = (int) Math.round(percent / 100.0 * width);
filled = Math.max(0, Math.min(filled, width));
return GREEN + "".repeat(filled) + RESET
+ DIM + "".repeat(width - filled) + RESET;
}
}
+32
View File
@@ -0,0 +1,32 @@
import java.util.List;
/**
* Bonus Task Sequential vs Multithreaded Comparison.
*
* Downloads all chunks one after another on the calling thread.
* This exists only for timing comparison with the multithreaded run;
* it demonstrates the speedup gained from parallel execution.
*/
public class SequentialDownloader {
private SequentialDownloader() {}
/**
* Runs each chunk sequentially on the current thread and returns
* the total elapsed time in milliseconds.
*/
public static long run(DownloadConfig config, List<ChunkStatus> chunks) {
long start = System.currentTimeMillis();
for (ChunkStatus chunk : chunks) {
System.out.printf("[Sequential] Chunk #%d starting (%.0f MB)%n",
chunk.getChunkId(), chunk.getChunkSizeMB());
DownloadWorker worker = new DownloadWorker(chunk, config);
worker.run(); // blocks until this chunk is fully "downloaded"
System.out.printf("[Sequential] Chunk #%d done in %.2fs%n",
chunk.getChunkId(), chunk.getDownloadDurationMs() / 1000.0);
}
return System.currentTimeMillis() - start;
}
}