Develop #1

Open
HadiSharifi wants to merge 4 commits from develop into main
5 changed files with 193 additions and 98 deletions
+92
View File
@@ -0,0 +1,92 @@
## Question 1: `start()` vs `run()`
### What output do you get from the program?
The first call (`t1.run()`) prints `Running in: main` because it executes on the **main thread** directly — no new thread is created. The second call (`t2.start()`) properly spawns a new thread, so it prints `Running in: Thread-2`.
The `Thread.sleep(100)` between the two calls ensures `t2`'s output isn't interleaved with the first, but the ordering of the second line is still technically non-deterministic (it will almost always appear after `"Calling start()"`).
### What's the difference between `start()` and `run()`?
| | `run()` | `start()` |
|---|---|---|
| **Execution** | Runs on the **calling thread** (like a normal method call) | Spawns a **new OS thread** and runs `run()` on it |
| **Concurrency** | None — sequential, blocking | Concurrent — the calling thread continues immediately |
| **Thread name** | Uses the calling thread's name (`main`) | Uses the new thread's name (`Thread-2`) |
| **Thread lifecycle** | Does not transition the thread to `RUNNABLE` state | Properly starts the thread lifecycle |
Calling `run()` directly is just a regular method call. Only `start()` actually creates a new thread.
---
## Question 2: Daemon Threads
### What output do you get from the program?
```
Main thread ends.
Daemon thread running...
Daemon thread running...
(possibly a few more lines, then the program exits abruptly)
```
The exact number of "Daemon thread running..." lines is non-deterministic — typically 0 to 2. The JVM shuts down as soon as the **main thread** finishes, which kills all remaining daemon threads immediately, regardless of what they're doing.
### What happens if you remove `thread.setDaemon(true)`?
The thread becomes a regular (non-daemon) **user thread**. The JVM will **not exit** until all user threads complete. In this case, the loop runs all 20 iterations (taking ~10 seconds), printing `"Daemon thread running..."` 20 times before the program ends.
### Real-life use cases of daemon threads
- **Garbage Collector** The JVM's own GC runs as a daemon thread; it should never prevent the JVM from shutting down.
- **Background logging** Flushing logs or metrics to a file/server periodically, where losing the last few entries on shutdown is acceptable.
- **Heartbeat / keep-alive threads** Sending periodic pings to a server while the application is alive.
- **Cache invalidation** A background thread that evicts stale entries from an in-memory cache.
- **Auto-save** Periodically saving a draft in an editor; the user closing the app shouldn't be blocked by this.
---
## Question 3: A Shorter Way to Create Threads (Lambda)
### What output do you get from the program?
```
Thread is running using a ...!
```
(Printed from the newly spawned thread.)
### What is the `() -> { ... }` syntax called?
It is called a **lambda expression** (introduced in Java 8). It provides a concise way to implement a **functional interface** — an interface with exactly one abstract method. Since `Runnable` has only one method (`run()`), a lambda can be used anywhere a `Runnable` is expected.
### How is this different from extending `Thread` or implementing `Runnable`?
| Approach | Code required | Reusability | Notes |
|---|---|---|---|
| `extends Thread` | Full class definition | Low — must subclass `Thread`, can't extend anything else | Tightly couples logic to thread machinery |
| `implements Runnable` | Full class + `new Thread(r)` | Higher — decouples task from thread | Preferred for named/reusable task classes |
| **Lambda** | One-liner inline | Low — anonymous, inline only | Best for short, one-off tasks |
The lambda approach is essentially **anonymous shorthand for `implements Runnable`** — the compiler generates an implementation of `Runnable.run()` under the hood. It is the most concise option but is best suited for simple, short tasks. For complex or reusable tasks, a named class implementing `Runnable` is clearer.
```java
// These three are functionally equivalent:
// 1. Class extending Thread
class MyThread extends Thread {
public void run() { System.out.println("Running"); }
}
new MyThread().start();
// 2. Anonymous Runnable
new Thread(new Runnable() {
public void run() { System.out.println("Running"); }
}).start();
// 3. Lambda (shortest)
new Thread(() -> System.out.println("Running")).start();
```
+22 -20
View File
@@ -1,12 +1,5 @@
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;
@@ -21,23 +14,32 @@ public class DownloadWorker implements Runnable {
@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.
long startTime = System.currentTimeMillis();
chunkStatus.setStartTimeMs(startTime);
System.out.println("Chunk: " + chunkStatus.getChunkId() + " 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.
long randomSleep = random.nextLong(config.getMinStepDelayMs(), config.getMaxStepDelayMs());
try {
Thread.sleep(randomSleep);
}
catch (InterruptedException e) {
System.out.println(e.getMessage());
}
double down = random.nextDouble();
downloaded = Math.min(downloaded + down, chunkStatus.getChunkSizeMB());
chunkStatus.setDownloadedMB(chunkStatus.getDownloadedMB() + down);
}
// TODO: Mark the chunk as completed.
// TODO: Record the chunk end time in chunkStatus.
// TODO: Print a message that this chunk has finished downloading.
chunkStatus.setCompleted(true);
Long endTime = System.currentTimeMillis();
chunkStatus.setEndTimeMs(endTime);
System.out.println("Chunk: " + chunkStatus.getChunkId() +
" has completed downloading (" + chunkStatus.getDownloadDurationMs() +" ms)");
}
}
+33 -47
View File
@@ -1,5 +1,6 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) {
@@ -19,13 +20,13 @@ public class Main {
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) {
@@ -34,50 +35,37 @@ public class Main {
workerThreads.add(workerThread);
// TODO:
// Students may print helpful debug information here,
// for example which chunk is assigned to which worker thread.
System.out.println("Assigned Worker-" + chunk.getChunkId()
+ " to chunk #" + chunk.getChunkId()
+ " (" + chunk.getChunkSizeMB() + " MB)");
}
// 4. Create and start monitor thread
System.out.println();
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();
for (Thread workerThread : workerThreads) {
workerThread.start();
}
// 5. Start worker threads
// TODO:
// Start each worker thread in workerThreads.
// Use a loop and call start() on each thread.
for (Thread workerThread : workerThreads) {
try {
workerThread.join();
} catch (InterruptedException e) {
System.out.println("Thread was interrupted: " + e.getMessage());
}
}
// 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();
// }
try {
monitorThread.join();
}
catch (InterruptedException e) {
System.out.println("Thread was interrupted: " + e.getMessage());
}
// 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 ===");
@@ -91,17 +79,15 @@ public class Main {
completedChunks++;
}
System.out.println(
"Chunk " + chunk.getChunkId()
+ ": " + chunk.getDownloadedMB()
+ "/" + chunk.getChunkSizeMB()
+ " MB"
);
System.out.printf(" Chunk %d: %.2f/%.0f MB | Duration: %d ms%n",
chunk.getChunkId(), chunk.getDownloadedMB(),
chunk.getChunkSizeMB(), chunk.getDownloadDurationMs());
}
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.");
System.out.println("Completed chunks : " + completedChunks + "/" + chunks.size());
System.out.printf("Downloaded total : %.2f/%d MB%n", downloadedMB, config.getTotalSizeMB());
}
}
+41 -26
View File
@@ -16,16 +16,7 @@ public class ProgressMonitor implements Runnable {
@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
double previousProgress = 0.0;
while (true) {
double totalDownloadedMB = 0.0;
@@ -44,25 +35,49 @@ public class ProgressMonitor implements Runnable {
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()
);
double deltaMB = totalDownloadedMB - previousProgress;
double speedMBps = deltaMB / (monitorDelayMs / 1000.0);
previousProgress = totalDownloadedMB;
// TODO:
// If all chunks are completed, print a final message and exit the loop
double remainingMB = totalSizeMB - totalDownloadedMB;
long etaSeconds = (speedMBps > 0) ? (long)(remainingMB / speedMBps) : 0;
try {
Thread.sleep(monitorDelayMs);
} catch (InterruptedException e) {
System.out.println("Progress monitor interrupted.");
return;
int barWidth = 30;
int filled = (int)(percent / 100.0 * barWidth);
filled = Math.min(filled, barWidth);
String bar = "=".repeat(filled) + (filled < barWidth ? ">" : "") + " ".repeat(Math.max(0, barWidth - filled - 1));
System.out.printf("\r[%-30s] %5.1f%% | %5.1f/%d MB | Speed: %.2f MB/s | ETA: %ds | Chunks: %d/%d ",
bar, percent, totalDownloadedMB, totalSizeMB,
speedMBps, etaSeconds,
completedChunks, chunks.size());
// System.out.printf(
// "Progress for %s: %.1f/%.1f MB (%.2f%%), completed chunks: %d/%d%n",
// fileName,
// totalDownloadedMB,
// (double) totalSizeMB,
// percent,
// completedChunks,
// chunks.size()
// );
if (completedChunks == chunks.size()) {
System.out.println("download completed!");
break;
} else {
try {
Thread.sleep(monitorDelayMs);
} catch (InterruptedException e) {
System.out.println("Progress monitor interrupted.");
return;
}
}
}
}
+5 -5
View File
@@ -1,7 +1,7 @@
fileName=movie.mkv
totalSizeMB=120
chunkCount=6
minStepDelayMs=80
maxStepDelayMs=200
minStepDownloadMB=2
maxStepDownloadMB=6
chunkCount=10
minStepDelayMs=200
maxStepDelayMs=600
minStepDownloadMB=.1
maxStepDownloadMB=.4