6. Java Date/Time, NIO File I/O & Multithreading
Chapters 21-24: java.time API, Path & Files, try-with-resources, Thread/Runnable, ExecutorService & CompletableFuture
Module 1: Date & Time API (java.time) & NIO File Operations
Using modern immutable date types and try-with-resources file management.
🇬🇧 English Definition
java.time provides modern immutable date/time classes (LocalDate, LocalDateTime, ZonedDateTime). java.nio.file.Path and Files offer modern filesystem utility operations with try-with-resources auto-closing.
🇮🇳 Hinglish Definition
java.time date aur time ke liye modern immutable classes deta hai. try-with-resources AutoCloseable files/streams ko automatically close karta hai.
Core Concepts & Rules
- LocalDate & Duration: LocalDate.now(); Duration.ofHours(5).toMinutes();
- try-with-resources: try (var reader = Files.newBufferedReader(path)) { ... }
🔍 Line-by-Line Code Breakdown
- Line 2: LocalDate.now() captures current system date.
- Line 3: Duration.ofHours(5).toMinutes() calculates duration minutes (300).
🎯 Interview Focus & Questions
- Q: Advantage of try-with-resources?
A: Automatically closes resources (files, sockets, DB connections) implementing AutoCloseable preventing memory leaks.
import java.time.*;
public class DateTimeDemo {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
Duration d = Duration.ofHours(5);
System.out.println("Date: " + today);
System.out.println("5 Hours in Minutes: " + d.toMinutes());
}
}
Module 2: Multithreading, Concurrency & CompletableFuture
Managing concurrent execution paths, synchronization, thread pools, and async futures.
🇬🇧 English Definition
Multithreading executes multiple concurrent threads. ExecutorService manages worker thread pools. CompletableFuture enables asynchronous pipeline composition.
🇮🇳 Hinglish Definition
Multithreading parallel tasks ke liye use hoti hai. ExecutorService thread pool manage karta hai aur CompletableFuture async pipeline compose karta hai.
Core Concepts & Rules
- Thread vs Runnable: Runnable separates task logic from thread execution.
- Synchronization: Prevents race conditions on shared mutable state.
- CompletableFuture: CompletableFuture.supplyAsync(...).thenApply(...).thenAccept(...);
🔍 Line-by-Line Code Breakdown
- Line 1: Import java.util.concurrent.CompletableFuture.
- Line 4-7: Asynchronous pipeline supplying 'Java', converting to uppercase, and printing.
🎯 Interview Focus & Questions
- Q: What is ExecutorService?
A: A high-level concurrency API managing worker thread pools and submitted tasks. - Q: What is synchronization?
A: Controlled access to shared mutable state avoiding race conditions.
import java.util.concurrent.CompletableFuture;
public class AsyncDemo {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> "Java Concurrency")
.thenApply(String::toUpperCase)
.thenAccept(System.out::println)
.join();
}
}