Here's your Telegram post for Day 23!
---
π Day 23: Mastering Java! Today we're diving into `try-with-resources`, a powerful feature introduced in Java 7 for efficient resource management. No more manual `finally` blocks to close resources! π `try-with-resources` automatically ensures that any resource opened in its declaration is closed once the `try` block finishes, whether normally or due to an exception. It makes your code cleaner, safer, and easier to maintain. Let's explore how it simplifies handling file streams and other resources! π‘
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ResourceManagementDemo {
public static void main(String[] args) {
// Imagine 'data.txt' exists and contains "Welcome to Day 23!"
// For actual execution, create a file named data.txt in your project root
// and add some text, e.g., "Welcome to Day 23!"
System.out.println("Attempting to read from data.txt...");
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String firstLine = reader.readLine();
System.out.println("Content read: " + firstLine);
} catch (IOException e) {
System.err.println("π¨ Failed to read file: " + e.getMessage());
System.err.println("Make sure 'data.txt' exists in the same directory!");
}
}
}
```
Output example:
```
Attempting to read from data.txt...
Content read: Welcome to Day 23!
```
*(If `data.txt` does not exist, you will see the error message.)*
Challenge for you! πͺ
Modify the code to write a few lines of text to a file named `output.txt` using `try-with-resources` with a `FileWriter`. Then, read and print those lines back to the console using another `try-with-resources` block! Don't forget to handle `IOException`! βοΈ
---
---
π Day 23: Mastering Java! Today we're diving into `try-with-resources`, a powerful feature introduced in Java 7 for efficient resource management. No more manual `finally` blocks to close resources! π `try-with-resources` automatically ensures that any resource opened in its declaration is closed once the `try` block finishes, whether normally or due to an exception. It makes your code cleaner, safer, and easier to maintain. Let's explore how it simplifies handling file streams and other resources! π‘
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ResourceManagementDemo {
public static void main(String[] args) {
// Imagine 'data.txt' exists and contains "Welcome to Day 23!"
// For actual execution, create a file named data.txt in your project root
// and add some text, e.g., "Welcome to Day 23!"
System.out.println("Attempting to read from data.txt...");
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String firstLine = reader.readLine();
System.out.println("Content read: " + firstLine);
} catch (IOException e) {
System.err.println("π¨ Failed to read file: " + e.getMessage());
System.err.println("Make sure 'data.txt' exists in the same directory!");
}
}
}
```
Output example:
```
Attempting to read from data.txt...
Content read: Welcome to Day 23!
```
*(If `data.txt` does not exist, you will see the error message.)*
Challenge for you! πͺ
Modify the code to write a few lines of text to a file named `output.txt` using `try-with-resources` with a `FileWriter`. Then, read and print those lines back to the console using another `try-with-resources` block! Don't forget to handle `IOException`! βοΈ
---
Which interface must a resource implement to be used in a try-with-resources statement?
Anonymous Quiz
13%
java.io.Serializable
13%
java.io.Closeable
13%
java.lang.AutoCloseable
63%
java.lang.Runnable
Hello, Java learners! π Welcome to **Day 24** of our journey!
Today, we're unlocking some of Java's most powerful and expressive features: **Lambda Expressions** and the **Streams API**. π These concepts are cornerstones of modern Java, allowing you to write more concise, readable, and functional code for data processing. Get ready to transform your collections with ease and elegance! Let's dive in and see how they make your code shine. β¨
---
```java
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class Day24StreamDemo {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println("Original numbers: " + numbers);
System.out.println("---");
// Example 1: Filtering even numbers and squaring them using Streams and Lambdas
List<Integer> squaredEvenNumbers = numbers.stream()
.filter(n -> n % 2 == 0) // Lambda as Predicate
.map(n -> n * n) // Lambda as Function
.collect(Collectors.toList()); // Terminal operation
System.out.println("Squared even numbers: " + squaredEvenNumbers);
System.out.println("---");
// Example 2: Sum of numbers greater than 5
long countGreaterThan5 = numbers.stream()
.filter(n -> n > 5) // Another Predicate lambda
.count(); // Terminal operation
System.out.println("Count of numbers greater than 5: " + countGreaterThan5);
System.out.println("---");
// Example 3: Finding the first odd number
Optional<Integer> firstOdd = numbers.stream()
.filter(n -> n % 2 != 0) // Predicate lambda
.findFirst(); // Terminal operation returning Optional
firstOdd.ifPresent(n -> System.out.println("First odd number: " + n)); // Lambda as Consumer
System.out.println("---");
}
}
```
---
Output example:
```
Original numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
---
Squared even numbers: [4, 16, 36, 64, 100]
---
Count of numbers greater than 5: 5
---
First odd number: 1
---
```
---
### Small Challenge:
Modify the `numbers` list. Can you find the *sum of the cubes* of all numbers less than 5? π€ Try to achieve this in a single stream pipeline!
---
Today, we're unlocking some of Java's most powerful and expressive features: **Lambda Expressions** and the **Streams API**. π These concepts are cornerstones of modern Java, allowing you to write more concise, readable, and functional code for data processing. Get ready to transform your collections with ease and elegance! Let's dive in and see how they make your code shine. β¨
---
```java
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class Day24StreamDemo {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println("Original numbers: " + numbers);
System.out.println("---");
// Example 1: Filtering even numbers and squaring them using Streams and Lambdas
List<Integer> squaredEvenNumbers = numbers.stream()
.filter(n -> n % 2 == 0) // Lambda as Predicate
.map(n -> n * n) // Lambda as Function
.collect(Collectors.toList()); // Terminal operation
System.out.println("Squared even numbers: " + squaredEvenNumbers);
System.out.println("---");
// Example 2: Sum of numbers greater than 5
long countGreaterThan5 = numbers.stream()
.filter(n -> n > 5) // Another Predicate lambda
.count(); // Terminal operation
System.out.println("Count of numbers greater than 5: " + countGreaterThan5);
System.out.println("---");
// Example 3: Finding the first odd number
Optional<Integer> firstOdd = numbers.stream()
.filter(n -> n % 2 != 0) // Predicate lambda
.findFirst(); // Terminal operation returning Optional
firstOdd.ifPresent(n -> System.out.println("First odd number: " + n)); // Lambda as Consumer
System.out.println("---");
}
}
```
---
Output example:
```
Original numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
---
Squared even numbers: [4, 16, 36, 64, 100]
---
Count of numbers greater than 5: 5
---
First odd number: 1
---
```
---
### Small Challenge:
Modify the `numbers` list. Can you find the *sum of the cubes* of all numbers less than 5? π€ Try to achieve this in a single stream pipeline!
---
Which of the following is NOT a terminal operation in Java Streams?
Anonymous Quiz
25%
filter()
25%
collect()
25%
forEach()
25%
reduce()
π **Day 25: Unit Testing (JUnit) - Making Your Java Code Bulletproof!** π
Hello, aspiring Java developers! Today marks a crucial milestone: diving into Unit Testing with JUnit. This isn't just about finding bugs; it's about building robust, reliable applications you can trust. JUnit is the de-facto standard for testing in Java, allowing us to write small, isolated tests for individual units of code (like a single method).
We'll learn how to structure tests, use the `@Test` annotation, and verify outcomes with powerful assertions like `assertEquals()`. Get ready to boost your code quality and confidently refactor! πͺ
---
```java
// src/main/java/com/example/app/Calculator.java
package com.example.app;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public boolean isPositive(int number) {
return number > 0;
}
}
```
```java
// src/test/java/com/example/app/CalculatorTest.java
package com.example.app;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*; // Import static for easier access to assertions
public class CalculatorTest {
@Test // Marks this method as a JUnit test
void testAddPositiveNumbers() {
Calculator calculator = new Calculator();
int expected = 5;
int actual = calculator.add(2, 3);
assertEquals(expected, actual, "Adding 2 and 3 should result in 5");
}
@Test
void testAddZeroToNumber() {
Calculator calculator = new Calculator();
assertEquals(10, calculator.add(10, 0), "Adding zero should return the original number");
}
@Test
void testIsPositiveTrue() {
Calculator calculator = new Calculator();
assertTrue(calculator.isPositive(5), "5 should be considered positive");
}
@Test
void testIsPositiveFalse() {
Calculator calculator = new Calculator();
assertFalse(calculator.isPositive(-2), "-2 should be considered not positive");
assertFalse(calculator.isPositive(0), "0 should be considered not positive");
}
}
```
---
Output example:
```
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
```
---
π‘ **Your Challenge:**
1. Add a new JUnit test method (`@Test`) called `testSubtractNegativeNumbers` in `CalculatorTest`.
2. Test the `subtract` method with negative numbers (e.g., `calculator.subtract(5, -2)` should be 7). Use `assertEquals()`.
3. Explore and use `assertNotEquals()` in another test case for your `Calculator` class (e.g., ensuring `add(2,2)` is not `5`).
Happy testing! π§ͺ
---
Hello, aspiring Java developers! Today marks a crucial milestone: diving into Unit Testing with JUnit. This isn't just about finding bugs; it's about building robust, reliable applications you can trust. JUnit is the de-facto standard for testing in Java, allowing us to write small, isolated tests for individual units of code (like a single method).
We'll learn how to structure tests, use the `@Test` annotation, and verify outcomes with powerful assertions like `assertEquals()`. Get ready to boost your code quality and confidently refactor! πͺ
---
```java
// src/main/java/com/example/app/Calculator.java
package com.example.app;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public boolean isPositive(int number) {
return number > 0;
}
}
```
```java
// src/test/java/com/example/app/CalculatorTest.java
package com.example.app;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*; // Import static for easier access to assertions
public class CalculatorTest {
@Test // Marks this method as a JUnit test
void testAddPositiveNumbers() {
Calculator calculator = new Calculator();
int expected = 5;
int actual = calculator.add(2, 3);
assertEquals(expected, actual, "Adding 2 and 3 should result in 5");
}
@Test
void testAddZeroToNumber() {
Calculator calculator = new Calculator();
assertEquals(10, calculator.add(10, 0), "Adding zero should return the original number");
}
@Test
void testIsPositiveTrue() {
Calculator calculator = new Calculator();
assertTrue(calculator.isPositive(5), "5 should be considered positive");
}
@Test
void testIsPositiveFalse() {
Calculator calculator = new Calculator();
assertFalse(calculator.isPositive(-2), "-2 should be considered not positive");
assertFalse(calculator.isPositive(0), "0 should be considered not positive");
}
}
```
---
Output example:
```
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
```
---
π‘ **Your Challenge:**
1. Add a new JUnit test method (`@Test`) called `testSubtractNegativeNumbers` in `CalculatorTest`.
2. Test the `subtract` method with negative numbers (e.g., `calculator.subtract(5, -2)` should be 7). Use `assertEquals()`.
3. Explore and use `assertNotEquals()` in another test case for your `Calculator` class (e.g., ensuring `add(2,2)` is not `5`).
Happy testing! π§ͺ
---
Which of the following annotations is used in JUnit 5 to mark a method as a test method?
Anonymous Quiz
14%
43%
43%
0%
π Day 26: Diving into Basic Web Scraping with Jsoup! πΈοΈ
Ever wondered how to programmatically extract information from websites? Today, we're unmasking the power of Jsoup, a fantastic Java library for working with real-world HTML. It makes fetching, parsing, and manipulating HTML documents a breeze. Get ready to turn web pages into structured data without breaking a sweat! Let's get scraping! β¨
```java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
public class BasicWebScraper {
public static void main(String[] args) {
String url = "https://en.wikipedia.org/wiki/Main_Page"; // Target URL
try {
// 1. Connect to the URL and fetch the HTML document
Document doc = Jsoup.connect(url).get();
// 2. Extract the page title
String pageTitle = doc.title();
System.out.println("Page Title: " + pageTitle);
// 3. Extract the text from the first <h1> tag
String firstH1 = doc.select("h1").first().text();
System.out.println("First H1 Heading: " + firstH1);
} catch (IOException e) {
System.err.println("Error fetching or parsing the URL: " + e.getMessage());
} catch (NullPointerException e) {
System.err.println("Could not find the specified element. " + e.getMessage());
}
}
}
```
Output example:
Page Title: Main Page - Wikipedia
First H1 Heading: Main Page
**Small challenge:**
Modify the code to extract the text from the *first paragraph* (`<p>` tag) on the Wikipedia main page! Can you find the correct selector? π€ Hint: `doc.select("p").first().text()` might be useful!
---
Ever wondered how to programmatically extract information from websites? Today, we're unmasking the power of Jsoup, a fantastic Java library for working with real-world HTML. It makes fetching, parsing, and manipulating HTML documents a breeze. Get ready to turn web pages into structured data without breaking a sweat! Let's get scraping! β¨
```java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
public class BasicWebScraper {
public static void main(String[] args) {
String url = "https://en.wikipedia.org/wiki/Main_Page"; // Target URL
try {
// 1. Connect to the URL and fetch the HTML document
Document doc = Jsoup.connect(url).get();
// 2. Extract the page title
String pageTitle = doc.title();
System.out.println("Page Title: " + pageTitle);
// 3. Extract the text from the first <h1> tag
String firstH1 = doc.select("h1").first().text();
System.out.println("First H1 Heading: " + firstH1);
} catch (IOException e) {
System.err.println("Error fetching or parsing the URL: " + e.getMessage());
} catch (NullPointerException e) {
System.err.println("Could not find the specified element. " + e.getMessage());
}
}
}
```
Output example:
Page Title: Main Page - Wikipedia
First H1 Heading: Main Page
**Small challenge:**
Modify the code to extract the text from the *first paragraph* (`<p>` tag) on the Wikipedia main page! Can you find the correct selector? π€ Hint: `doc.select("p").first().text()` might be useful!
---
Wikipedia
Welcome to Wikipedia
Area commands were the major operational and administrative formations of the Royal Australian Air Force (RAAF) between 1940 and 1954. Four commands were raised in 1940, early in World War II, to oversee operations, training and maintenance within their geographicalβ¦
Which Jsoup method chain is typically used to establish a connection to a URL and retrieve its HTML content as a `Document` object?
Anonymous Quiz
43%
Jsoup.parse(url)
14%
Jsoup.load(url)
43%
Jsoup.connect(url).get()
0%
Jsoup.fetch(url)
π Day 27 is here, and we're diving into a game-changer: Spring Boot! β¨
Tired of complex configurations? Spring Boot simplifies Java development, letting you build robust, production-ready applications with minimal fuss. It's built on top of the Spring Framework but takes away much of the boilerplate thanks to auto-configuration and embedded servers. Let's write our first 'Hello World' with Spring Boot and see its magic!
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
// The @SpringBootApplication annotation is a convenience annotation that combines:
// @Configuration, @EnableAutoConfiguration, and @ComponentScan.
@SpringBootApplication
@RestController // Makes this class capable of handling web requests
public class Day27Application {
public static void main(String[] args) {
SpringApplication.run(Day27Application.class, args);
}
@GetMapping("/hello") // Maps HTTP GET requests to the /hello path
public String hello() {
return "Hello from Spring Boot!";
}
}
```
Output example:
(After running the application and navigating to `http://localhost:8080/hello` in your browser or using `curl`):
`Hello from Spring Boot!`
π€ Small challenge:
1. Add another endpoint, e.g., `/greet` that returns "Greetings, Java Learner!" π‘
2. Bonus: Try changing the default port (8080) to something else (e.g., 8081) using an `application.properties` file!
---
Tired of complex configurations? Spring Boot simplifies Java development, letting you build robust, production-ready applications with minimal fuss. It's built on top of the Spring Framework but takes away much of the boilerplate thanks to auto-configuration and embedded servers. Let's write our first 'Hello World' with Spring Boot and see its magic!
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
// The @SpringBootApplication annotation is a convenience annotation that combines:
// @Configuration, @EnableAutoConfiguration, and @ComponentScan.
@SpringBootApplication
@RestController // Makes this class capable of handling web requests
public class Day27Application {
public static void main(String[] args) {
SpringApplication.run(Day27Application.class, args);
}
@GetMapping("/hello") // Maps HTTP GET requests to the /hello path
public String hello() {
return "Hello from Spring Boot!";
}
}
```
Output example:
(After running the application and navigating to `http://localhost:8080/hello` in your browser or using `curl`):
`Hello from Spring Boot!`
π€ Small challenge:
1. Add another endpoint, e.g., `/greet` that returns "Greetings, Java Learner!" π‘
2. Bonus: Try changing the default port (8080) to something else (e.g., 8081) using an `application.properties` file!
---
Here's your Telegram post for Day 30!
---
π **Congratulations on Reaching Day 30!** π
You've made incredible progress in just thirty days, diving into Java fundamentals! π Now it's time to consolidate all your learning with a final project. How about building a simple *Command-Line To-Do List Manager*? π It's a fantastic way to apply your understanding of classes, objects, methods, `ArrayList`s, and user input. Let's review some core concepts and get you thinking!
Hereβs a quick look at a basic `Task` class and how you might manage a list of them:
```java
import java.util.ArrayList;
import java.util.List;
// Represents a single To-Do item
class Task {
private String description;
private boolean isCompleted;
public Task(String description) {
this.description = description;
this.isCompleted = false; // By default, a new task is not completed
}
public String getDescription() {
return description;
}
public boolean isCompleted() {
return isCompleted;
}
public void markCompleted() {
this.isCompleted = true;
}
@Override
public String toString() {
return "[" + (isCompleted ? "β " : "β³") + "] " + description;
}
}
// Main class to demonstrate To-Do list management
public class Day30Review {
public static void main(String[] args) {
List<Task> myTasks = new ArrayList<>(); // Use ArrayList for dynamic size
System.out.println("--- Initial To-Do List ---");
myTasks.add(new Task("Learn Java basics"));
myTasks.add(new Task("Start final project idea"));
myTasks.add(new Task("Review OOP concepts"));
for (Task task : myTasks) {
System.out.println(task);
}
System.out.println("n--- Updating Task Status ---");
// Mark the first task as completed
if (!myTasks.isEmpty()) {
myTasks.get(0).markCompleted();
System.out.println("Marked '" + myTasks.get(0).getDescription() + "' as completed.");
}
System.out.println("n--- Updated To-Do List ---");
for (Task task : myTasks) {
System.out.println(task);
}
}
}
```
Output example:
```
--- Initial To-Do List ---
[β³] Learn Java basics
[β³] Start final project idea
[β³] Review OOP concepts
--- Updating Task Status ---
Marked 'Learn Java basics' as completed.
--- Updated To-Do List ---
[β ] Learn Java basics
[β³] Start final project idea
[β³] Review OOP concepts
```
### Small Challenge:
Your challenge for your To-Do List Manager:
1. **Add User Input:** Implement `Scanner` to allow users to add new tasks.
2. **Remove Tasks:** Create a method that allows users to remove tasks by their index in the list.
3. **List by Status:** Add functionality to display *only* completed tasks or *only* pending tasks.
Ready to build something awesome? You've got this! πͺ Don't forget to share your progress! #JavaLearning #Day30 #FinalProject #CodingChallenge
---
---
π **Congratulations on Reaching Day 30!** π
You've made incredible progress in just thirty days, diving into Java fundamentals! π Now it's time to consolidate all your learning with a final project. How about building a simple *Command-Line To-Do List Manager*? π It's a fantastic way to apply your understanding of classes, objects, methods, `ArrayList`s, and user input. Let's review some core concepts and get you thinking!
Hereβs a quick look at a basic `Task` class and how you might manage a list of them:
```java
import java.util.ArrayList;
import java.util.List;
// Represents a single To-Do item
class Task {
private String description;
private boolean isCompleted;
public Task(String description) {
this.description = description;
this.isCompleted = false; // By default, a new task is not completed
}
public String getDescription() {
return description;
}
public boolean isCompleted() {
return isCompleted;
}
public void markCompleted() {
this.isCompleted = true;
}
@Override
public String toString() {
return "[" + (isCompleted ? "β " : "β³") + "] " + description;
}
}
// Main class to demonstrate To-Do list management
public class Day30Review {
public static void main(String[] args) {
List<Task> myTasks = new ArrayList<>(); // Use ArrayList for dynamic size
System.out.println("--- Initial To-Do List ---");
myTasks.add(new Task("Learn Java basics"));
myTasks.add(new Task("Start final project idea"));
myTasks.add(new Task("Review OOP concepts"));
for (Task task : myTasks) {
System.out.println(task);
}
System.out.println("n--- Updating Task Status ---");
// Mark the first task as completed
if (!myTasks.isEmpty()) {
myTasks.get(0).markCompleted();
System.out.println("Marked '" + myTasks.get(0).getDescription() + "' as completed.");
}
System.out.println("n--- Updated To-Do List ---");
for (Task task : myTasks) {
System.out.println(task);
}
}
}
```
Output example:
```
--- Initial To-Do List ---
[β³] Learn Java basics
[β³] Start final project idea
[β³] Review OOP concepts
--- Updating Task Status ---
Marked 'Learn Java basics' as completed.
--- Updated To-Do List ---
[β ] Learn Java basics
[β³] Start final project idea
[β³] Review OOP concepts
```
### Small Challenge:
Your challenge for your To-Do List Manager:
1. **Add User Input:** Implement `Scanner` to allow users to add new tasks.
2. **Remove Tasks:** Create a method that allows users to remove tasks by their index in the list.
3. **List by Status:** Add functionality to display *only* completed tasks or *only* pending tasks.
Ready to build something awesome? You've got this! πͺ Don't forget to share your progress! #JavaLearning #Day30 #FinalProject #CodingChallenge
---
Which of the following concepts is NOT directly demonstrated or primarily used in the provided `Day30Review` Java code for the To-Do List idea?
Anonymous Quiz
33%
A. Object-Oriented Programming (OOP) principles like encapsulation.
0%
B. Dynamic data structures using `ArrayList`.
33%
C. Basic input/output operations for user interaction.
33%
D. Iterating over collections using a for-each loop.
Here's your Telegram post for Day 31 of your Java learning series!
---
π Day 31: Ready to unlock the next level of Java concurrency?
Traditional threads are heavy, but Project Loom introduces **Virtual Threads**, lightweight wonders that revolutionize how we build scalable applications! π€― Imagine handling millions of concurrent tasks with ease, dramatically simplifying your code. We'll explore how Loom is driving a **Reactive Renaissance**, making complex asynchronous systems more manageable and efficient. Get ready to architect scalable futures! β¨
```java
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class VirtualThreadsDemo {
public static void main(String[] args) throws InterruptedException {
int numberOfTasks = 1_000_000; // Let's create a million "lightweight" tasks!
System.out.println("Starting " + numberOfTasks + " virtual tasks...");
Instant start = Instant.now();
// Using Executors.newVirtualThreadPerTaskExecutor() creates a new virtual thread
// for each submitted task, showcasing Loom's efficiency.
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, numberOfTasks).forEach(i ->
executor.submit(() -> {
// Simulate some work, perhaps a tiny delay or computation
try {
// In a real scenario, this might involve I/O operations
// which Virtual Threads are designed to efficiently handle.
// Thread.sleep(1); // Uncomment to simulate a tiny blocking operation per task
} catch (Exception e) {
Thread.currentThread().interrupt();
}
// System.out.println("Task " + i + " on " + Thread.currentThread().getName());
// (Commented out to avoid overwhelming console output)
})
);
} // The ExecutorService is automatically shut down here, waiting for all tasks.
Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println("All " + numberOfTasks + " tasks completed in " + duration.toMillis() + " ms.");
}
}
```
Output example:
```
Starting 1000000 virtual tasks...
All 1000000 tasks completed in XXX ms.
```
*(The `XXX` will be a relatively small number, demonstrating the speed of creating and managing a million virtual threads compared to traditional threads.)*
π‘ **Challenge Time!**
Modify the code to:
1. Run the same `numberOfTasks` using a traditional thread pool, e.g., `Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())` or `Executors.newCachedThreadPool()`.
2. Compare the execution time and observe any differences. What limitations or overheads do you encounter with traditional threads that Virtual Threads overcome? (Hint: Think about thread creation cost and memory footprint!).
---
---
π Day 31: Ready to unlock the next level of Java concurrency?
Traditional threads are heavy, but Project Loom introduces **Virtual Threads**, lightweight wonders that revolutionize how we build scalable applications! π€― Imagine handling millions of concurrent tasks with ease, dramatically simplifying your code. We'll explore how Loom is driving a **Reactive Renaissance**, making complex asynchronous systems more manageable and efficient. Get ready to architect scalable futures! β¨
```java
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class VirtualThreadsDemo {
public static void main(String[] args) throws InterruptedException {
int numberOfTasks = 1_000_000; // Let's create a million "lightweight" tasks!
System.out.println("Starting " + numberOfTasks + " virtual tasks...");
Instant start = Instant.now();
// Using Executors.newVirtualThreadPerTaskExecutor() creates a new virtual thread
// for each submitted task, showcasing Loom's efficiency.
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, numberOfTasks).forEach(i ->
executor.submit(() -> {
// Simulate some work, perhaps a tiny delay or computation
try {
// In a real scenario, this might involve I/O operations
// which Virtual Threads are designed to efficiently handle.
// Thread.sleep(1); // Uncomment to simulate a tiny blocking operation per task
} catch (Exception e) {
Thread.currentThread().interrupt();
}
// System.out.println("Task " + i + " on " + Thread.currentThread().getName());
// (Commented out to avoid overwhelming console output)
})
);
} // The ExecutorService is automatically shut down here, waiting for all tasks.
Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println("All " + numberOfTasks + " tasks completed in " + duration.toMillis() + " ms.");
}
}
```
Output example:
```
Starting 1000000 virtual tasks...
All 1000000 tasks completed in XXX ms.
```
*(The `XXX` will be a relatively small number, demonstrating the speed of creating and managing a million virtual threads compared to traditional threads.)*
π‘ **Challenge Time!**
Modify the code to:
1. Run the same `numberOfTasks` using a traditional thread pool, e.g., `Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())` or `Executors.newCachedThreadPool()`.
2. Compare the execution time and observe any differences. What limitations or overheads do you encounter with traditional threads that Virtual Threads overcome? (Hint: Think about thread creation cost and memory footprint!).
---