(init): Starting the project
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
// Educational simplification:
|
||||
// each worker writes only to its own ChunkStatus,
|
||||
// and the monitor only reads chunk states.
|
||||
// volatile is used here to make progress updates more visible across threads.
|
||||
|
||||
/**
|
||||
* Represents the state and download progress of a single file chunk.
|
||||
* Each worker thread updates its own ChunkStatus, while the monitor thread reads it.
|
||||
*/
|
||||
public class ChunkStatus {
|
||||
private final int chunkId;
|
||||
private final double chunkSizeMB;
|
||||
private volatile double downloadedMB;
|
||||
private volatile boolean completed;
|
||||
private volatile long startTimeMs;
|
||||
private volatile long endTimeMs;
|
||||
|
||||
/**
|
||||
* Initializes a chunk with its unique ID and total allocated size.
|
||||
* Progress-related fields are initialized to default values.
|
||||
*/
|
||||
public ChunkStatus(int chunkId, double chunkSizeMB) {
|
||||
this.chunkId = chunkId;
|
||||
this.chunkSizeMB = chunkSizeMB;
|
||||
this.downloadedMB = 0.0;
|
||||
this.completed = false;
|
||||
this.startTimeMs = 0;
|
||||
this.endTimeMs = 0;
|
||||
}
|
||||
|
||||
// Getters and Setters
|
||||
public int getChunkId() {
|
||||
return chunkId;
|
||||
}
|
||||
|
||||
public double getChunkSizeMB() {
|
||||
return chunkSizeMB;
|
||||
}
|
||||
|
||||
public double getDownloadedMB() {
|
||||
return downloadedMB;
|
||||
}
|
||||
|
||||
public void setDownloadedMB(double downloadedMB) {
|
||||
// Guard to prevent downloaded size exceeding actual chunk size
|
||||
if (downloadedMB >= this.chunkSizeMB) {
|
||||
this.downloadedMB = this.chunkSizeMB;
|
||||
} else {
|
||||
this.downloadedMB = downloadedMB;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isCompleted() {
|
||||
return completed;
|
||||
}
|
||||
|
||||
public void setCompleted(boolean completed) {
|
||||
this.completed = completed;
|
||||
}
|
||||
|
||||
public long getStartTimeMs() {
|
||||
return startTimeMs;
|
||||
}
|
||||
|
||||
public void setStartTimeMs(long startTimeMs) {
|
||||
this.startTimeMs = startTimeMs;
|
||||
}
|
||||
|
||||
public long getEndTimeMs() {
|
||||
return endTimeMs;
|
||||
}
|
||||
|
||||
public void setEndTimeMs(long endTimeMs) {
|
||||
this.endTimeMs = endTimeMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to calculate the duration of this specific chunk's download.
|
||||
* Returns 0 if the chunk hasn't started or finished yet.
|
||||
*/
|
||||
public long getDownloadDurationMs() {
|
||||
if (startTimeMs > 0 && endTimeMs > startTimeMs) {
|
||||
return endTimeMs - startTimeMs;
|
||||
} else if (startTimeMs > 0 && !completed) {
|
||||
return System.currentTimeMillis() - startTimeMs;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to calculate the download percentage of this chunk.
|
||||
*/
|
||||
public double getProgressPercentage() {
|
||||
if (chunkSizeMB == 0) return 100.0;
|
||||
return (downloadedMB / chunkSizeMB) * 100.0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("Chunk #%d: %.1f/%.1f MB (%.1f%%)%s",
|
||||
chunkId,
|
||||
downloadedMB,
|
||||
chunkSizeMB,
|
||||
getProgressPercentage(),
|
||||
completed ? " [Completed]" : ""
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Utility methods related to chunk creation.
|
||||
*/
|
||||
public class ChunkUtils {
|
||||
|
||||
private ChunkUtils() {
|
||||
// Utility class
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits the total file size into a list of chunks.
|
||||
* Chunk sizes are as even as possible.
|
||||
* If the size is not exactly divisible, the last chunk gets the remainder.
|
||||
*
|
||||
* @param totalSizeMB total file size in MB
|
||||
* @param chunkCount number of chunks
|
||||
* @return list of ChunkStatus objects
|
||||
*/
|
||||
public static List<ChunkStatus> createChunks(int totalSizeMB, int chunkCount) {
|
||||
List<ChunkStatus> chunks = new ArrayList<>();
|
||||
|
||||
if (totalSizeMB <= 0 || chunkCount <= 0) {
|
||||
return chunks;
|
||||
}
|
||||
|
||||
int baseChunkSize = totalSizeMB / chunkCount;
|
||||
int remainder = totalSizeMB % chunkCount;
|
||||
|
||||
for (int i = 0; i < chunkCount; i++) {
|
||||
int chunkSize = baseChunkSize;
|
||||
|
||||
if (i == chunkCount - 1) {
|
||||
chunkSize += remainder;
|
||||
}
|
||||
|
||||
// Create one ChunkStatus object for each chunk.
|
||||
// chunkId is the chunk number, and chunkSize is this chunk's total size.
|
||||
chunks.add(new ChunkStatus(i + 1, chunkSize));
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
public class ConfigReader {
|
||||
|
||||
public static DownloadConfig readConfig(String fileName) {
|
||||
InputStream inputStream = ConfigReader.class.getClassLoader().getResourceAsStream(fileName);
|
||||
|
||||
if (inputStream == null) {
|
||||
throw new IllegalArgumentException("Config file not found in resources: " + fileName);
|
||||
}
|
||||
|
||||
String configFileName = null;
|
||||
int totalSizeMB = 0;
|
||||
int chunkCount = 0;
|
||||
int minStepDelayMs = 0;
|
||||
int maxStepDelayMs = 0;
|
||||
double minStepDownloadMB = 0;
|
||||
double maxStepDownloadMB = 0;
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
|
||||
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
line = line.trim();
|
||||
|
||||
if (line.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String[] parts = line.split("=", 2);
|
||||
if (parts.length != 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String key = parts[0].trim();
|
||||
String value = parts[1].trim();
|
||||
|
||||
switch (key) {
|
||||
case "fileName":
|
||||
configFileName = value;
|
||||
break;
|
||||
case "totalSizeMB":
|
||||
totalSizeMB = Integer.parseInt(value);
|
||||
break;
|
||||
case "chunkCount":
|
||||
chunkCount = Integer.parseInt(value);
|
||||
break;
|
||||
case "minStepDelayMs":
|
||||
minStepDelayMs = Integer.parseInt(value);
|
||||
break;
|
||||
case "maxStepDelayMs":
|
||||
maxStepDelayMs = Integer.parseInt(value);
|
||||
break;
|
||||
case "minStepDownloadMB":
|
||||
minStepDownloadMB = Double.parseDouble(value);
|
||||
break;
|
||||
case "maxStepDownloadMB":
|
||||
maxStepDownloadMB = Double.parseDouble(value);
|
||||
break;
|
||||
default:
|
||||
// Ignore unknown keys to keep parsing simple
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Error reading config file: " + fileName, e);
|
||||
}
|
||||
|
||||
return new DownloadConfig(
|
||||
configFileName,
|
||||
totalSizeMB,
|
||||
chunkCount,
|
||||
minStepDelayMs,
|
||||
maxStepDelayMs,
|
||||
minStepDownloadMB,
|
||||
maxStepDownloadMB
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Represents the configuration parameters for the simulated download manager.
|
||||
* This class is immutable to ensure thread-safety when shared among worker threads.
|
||||
*/
|
||||
public class DownloadConfig {
|
||||
private final String fileName;
|
||||
private final int totalSizeMB;
|
||||
private final int chunkCount;
|
||||
private final int minStepDelayMs;
|
||||
private final int maxStepDelayMs;
|
||||
private final double minStepDownloadMB;
|
||||
private final double maxStepDownloadMB;
|
||||
|
||||
/**
|
||||
* Constructs a new DownloadConfig with specified simulation parameters.
|
||||
*/
|
||||
public DownloadConfig(String fileName, int totalSizeMB, int chunkCount,
|
||||
int minStepDelayMs, int maxStepDelayMs,
|
||||
double minStepDownloadMB, double maxStepDownloadMB) {
|
||||
this.fileName = fileName;
|
||||
this.totalSizeMB = totalSizeMB;
|
||||
this.chunkCount = chunkCount;
|
||||
this.minStepDelayMs = minStepDelayMs;
|
||||
this.maxStepDelayMs = maxStepDelayMs;
|
||||
this.minStepDownloadMB = minStepDownloadMB;
|
||||
this.maxStepDownloadMB = maxStepDownloadMB;
|
||||
}
|
||||
|
||||
// Getters
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
public int getTotalSizeMB() {
|
||||
return totalSizeMB;
|
||||
}
|
||||
|
||||
public int getChunkCount() {
|
||||
return chunkCount;
|
||||
}
|
||||
|
||||
public int getMinStepDelayMs() {
|
||||
return minStepDelayMs;
|
||||
}
|
||||
|
||||
public int getMaxStepDelayMs() {
|
||||
return maxStepDelayMs;
|
||||
}
|
||||
|
||||
public double getMinStepDownloadMB() {
|
||||
return minStepDownloadMB;
|
||||
}
|
||||
|
||||
public double getMaxStepDownloadMB() {
|
||||
return maxStepDownloadMB;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DownloadConfig{" +
|
||||
"fileName='" + fileName + '\'' +
|
||||
", totalSizeMB=" + totalSizeMB +
|
||||
", chunkCount=" + chunkCount +
|
||||
", minStepDelayMs=" + minStepDelayMs +
|
||||
", maxStepDelayMs=" + maxStepDelayMs +
|
||||
", minStepDownloadMB=" + minStepDownloadMB +
|
||||
", maxStepDownloadMB=" + maxStepDownloadMB +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
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>
|
||||
*/
|
||||
public class DownloadWorker implements Runnable {
|
||||
|
||||
private final ChunkStatus chunkStatus;
|
||||
private final DownloadConfig config;
|
||||
private final Random random;
|
||||
|
||||
public DownloadWorker(ChunkStatus chunkStatus, DownloadConfig config) {
|
||||
this.chunkStatus = chunkStatus;
|
||||
this.config = config;
|
||||
this.random = new Random();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// TODO: Record the chunk start time in chunkStatus.
|
||||
double downloaded = 0.0;
|
||||
|
||||
// TODO: Print a message that this chunk has started downloading.
|
||||
|
||||
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.
|
||||
}
|
||||
|
||||
// TODO: Mark the chunk as completed.
|
||||
// TODO: Record the chunk end time in chunkStatus.
|
||||
// TODO: Print a message that this chunk has finished downloading.
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("=== Simulated Download Manager ===");
|
||||
|
||||
// 1. Read config
|
||||
DownloadConfig config;
|
||||
try {
|
||||
config = ConfigReader.readConfig("download_config.txt");
|
||||
} catch (Exception e) {
|
||||
System.out.println("Failed to read configuration: " + e.getMessage());
|
||||
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();
|
||||
|
||||
// 2. Create chunks
|
||||
List<ChunkStatus> chunks = ChunkUtils.createChunks(
|
||||
config.getTotalSizeMB(),
|
||||
config.getChunkCount()
|
||||
);
|
||||
|
||||
// 3. Create worker threads
|
||||
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.
|
||||
}
|
||||
|
||||
// 4. Create and start monitor thread
|
||||
ProgressMonitor monitor = new ProgressMonitor(config, chunks);
|
||||
Thread monitorThread = new Thread(monitor, "Progress-Monitor");
|
||||
|
||||
// TODO:
|
||||
// Start the monitor thread before starting the workers
|
||||
// so that progress can be displayed while downloading happens.
|
||||
//
|
||||
// Example idea:
|
||||
// monitorThread.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,
|
||||
|
||||
// 7. Print final report
|
||||
System.out.println();
|
||||
System.out.println("=== Final Report ===");
|
||||
|
||||
int completedChunks = 0;
|
||||
double downloadedMB = 0.0;
|
||||
|
||||
for (ChunkStatus chunk : chunks) {
|
||||
downloadedMB += chunk.getDownloadedMB();
|
||||
|
||||
if (chunk.isCompleted()) {
|
||||
completedChunks++;
|
||||
}
|
||||
|
||||
System.out.println(
|
||||
"Chunk " + chunk.getChunkId()
|
||||
+ ": " + chunk.getDownloadedMB()
|
||||
+ "/" + chunk.getChunkSizeMB()
|
||||
+ " MB"
|
||||
);
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("Completed chunks: " + completedChunks + "/" + chunks.size());
|
||||
System.out.println("Downloaded total: " + downloadedMB + "/" + config.getTotalSizeMB() + " MB");
|
||||
System.out.println("Simulation finished.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import java.util.List;
|
||||
|
||||
public class ProgressMonitor implements Runnable {
|
||||
|
||||
private final String fileName;
|
||||
private final int totalSizeMB;
|
||||
private final List<ChunkStatus> chunks;
|
||||
private final long monitorDelayMs;
|
||||
|
||||
public ProgressMonitor(DownloadConfig config, List<ChunkStatus> chunks) {
|
||||
this.fileName = config.getFileName();
|
||||
this.totalSizeMB = config.getTotalSizeMB();
|
||||
this.chunks = chunks;
|
||||
this.monitorDelayMs = 500;
|
||||
}
|
||||
|
||||
@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
|
||||
|
||||
|
||||
while (true) {
|
||||
double totalDownloadedMB = 0.0;
|
||||
int completedChunks = 0;
|
||||
|
||||
for (ChunkStatus chunk : chunks) {
|
||||
totalDownloadedMB += chunk.getDownloadedMB();
|
||||
|
||||
if (chunk.isCompleted()) {
|
||||
completedChunks++;
|
||||
}
|
||||
}
|
||||
|
||||
double percent = 0.0;
|
||||
if (totalSizeMB > 0) {
|
||||
percent = (totalDownloadedMB * 100.0) / totalSizeMB;
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
try {
|
||||
Thread.sleep(monitorDelayMs);
|
||||
} catch (InterruptedException e) {
|
||||
System.out.println("Progress monitor interrupted.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
fileName=movie.mkv
|
||||
totalSizeMB=120
|
||||
chunkCount=6
|
||||
minStepDelayMs=80
|
||||
maxStepDelayMs=200
|
||||
minStepDownloadMB=2
|
||||
maxStepDownloadMB=6
|
||||
Reference in New Issue
Block a user