• Файл

Валерій

Професор кафедри розробки програмного забезпечення

Місто:
Київ

Контактна інформація

Шукач вказав телефон .

Прізвище, контакти та світлина доступні тільки для зареєстрованих роботодавців. Щоб отримати доступ до особистих даних кандидатів, увійдіть як роботодавець або зареєструйтеся.

Завантажений файл

Файл містить ще 33 сторінки

Версія для швидкого перегляду

Це резюме розміщено у вигляді файлу. Ця версія для швидкого перегляду може бути гіршою за оригінал резюме.

Lecture Slides & Handouts: Concurrency in Java
Course: Advanced Java Programming
Level: University
Duration: 2-3 Lectures (90-120 minutes each)

Slide 1: Title Slide
Title: Concurrency in Java
Subtitle: Threads, Synchronization, and Parallel Execution
Instructor: [Your Name]
Date: [Current Date]

Slide 2: Learning Objectives
By the end of this lecture, students will be able to:
1. Understand the basics of concurrency and multithreading.
2. Create and manage threads in Java using Thread and Runnable.
3. Use thread synchronization (synchronized, volatile, Lock).
4. Handle thread communication (wait(), notify(), notifyAll()).
5. Work with high-level concurrency utilities (ExecutorService, Future, Concurrent Collections).
6. Avoid common concurrency issues (deadlocks, race conditions).

Slide 3: What is Concurrency?
Definition:
• Concurrency means multiple tasks executing overlapping periods (not necessarily simultaneously).
• Parallelism is a subset of concurrency where tasks run simultaneously (multi-core CPUs).
Example:
• A web server handling multiple requests at once.
• A video game rendering graphics while processing user input.

Slide 4: Threads in Java
Ways to Create Threads:
1. Extending Thread class
java
Copy
Download
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Starts the thread
}
}
2. Implementing Runnable (Preferred, more flexible)
java
Copy
Download
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running.");
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}

Slide 5: Thread Lifecycle
States:
1. NEW – Created but not started.
2. RUNNABLE – Executing in JVM.
3. BLOCKED/WAITING – Waiting for a monitor lock.
4. TIMED_WAITING – Sleeping for a specified time.
5. TERMINATED – Thread has finished execution.
Diagram:
Copy
Download
NEW → start() → RUNNABLE → run() completes → TERMINATED

BLOCKED/WAITING (if synchronized/wait())

Slide 6: Thread Synchronization
Problem: Race Condition
java
Copy
Download
class Counter {
private int count = 0;
public void increment() { count++; } // Not thread-safe!
}
• If two threads call increment() simultaneously, count may not update correctly.
Solution: synchronized Keyword
java
Copy
Download
public synchronized void increment() { count++; }
• Ensures only one thread executes the method at a time.

Slide 7: volatile Keyword
• Ensures variable visibility across threads (no caching).
java
Copy
Download
class SharedData {
private volatile boolean flag = true;
}
• Use when a variable is modified by one thread and read by others.

**Slide 8: Thread Communication (wait(), notify())
Example: Producer-Consumer Problem
java
Copy
Download
class Buffer {
private int data;
private boolean available = false;

public synchronized void produce(int value) throws InterruptedException {
while (available) wait(); // Wait if data is not consumed
data = value;
available = true;
notify(); // Notify consumer
}

public synchronized int consume() throws InterruptedException {
while (!available) wait(); // Wait if no data
available = false;
notify(); // Notify producer
return data;
}
}

Slide 9: High-Level Concurrency Utilities
1. ExecutorService (Thread Pools)
java
Copy
Download
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Task running"));
executor.shutdown();
2. Future (Get Result from Thread)
java
Copy
Download
Future<Integer> future = executor.submit(() -> 5 + 3);
System.out.println(future.get()); // Blocks until result is ready
3. ConcurrentHashMap (Thread-Safe Map)
java
Copy
Download
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 10);

Slide 10: Common Concurrency Issues
1. Deadlock – Two threads waiting for each other indefinitely.
java
Copy
Download
// Thread 1: locks A, then tries B
// Thread 2: locks B, then tries A
Solution: Avoid circular waits.
2. Starvation – A thread never gets CPU time.
Solution: Fair locks (ReentrantLock(true)).
3. Livelock – Threads keep retrying but make no progress.

Slide 11: Best Practices
✔ Prefer ExecutorService over raw Thread management.
✔ Use ConcurrentHashMap, CopyOnWriteArrayList instead of manual synchronization.
✔ Avoid synchronized blocks where possible (use Lock for finer control).
✔ Always handle InterruptedException.

Handout: Summary & Exercises
Key Takeaways:
• Threads allow concurrent execution.
• Synchronization (synchronized, volatile, Lock) prevents race conditions.
• High-level utilities (ExecutorService, Future) simplify concurrency.
Exercises:
1. Implement a multithreaded bank account with deposit/withdraw methods.
2. Solve the producer-consumer problem using BlockingQueue.
3. Find and fix a deadlock in a given code snippet.

Conclusion
Concurrency is powerful but requires careful handling. Java provides robust tools (Thread, synchronized, ExecutorService) to manage it effectively.
Next Lecture: Parallel Streams & CompletableFuture

Lecture Slides & Handouts: Parallel Streams & CompletableFuture in Java
Course: Advanced Java Programming
Level: University
Duration: 1-2 Lectures (90-120 minutes)

Slide 1: Title Slide
Title: Parallel Streams & CompletableFuture
Subtitle: Asynchronous and Parallel Programming in Java
Instructor: [Your Name]
Date: [Current Date]

Slide 2: Learning Objectives
By the end of this lecture, students will be able to:
1. Understand parallel streams and their performance implications.
2. Use CompletableFuture for asynchronous programming.
3. Chain multiple async operations (thenApply, thenAccept, thenCombine).
4. Handle errors in async workflows (exceptionally, handle).
5. Compare ForkJoinPool vs. custom thread pools in parallel streams.

Slide 3: Parallel Streams
What are Parallel Streams?
• Streams that execute operations concurrently using multiple threads.
• Built on ForkJoinPool.commonPool().
Example: Sequential vs. Parallel Stream
java
Copy
Download
List<Integer> numbers = List.of(1, 2, 3, 4, 5);

// Sequential
long sumSequential = numbers.stream().reduce(0, Integer::sum);

// Parallel (faster for large datasets)
long sumParallel = numbers.parallelStream().reduce(0, Integer::sum);
When to Use Parallel Streams?
✔ Large datasets
✔ Stateless, independent operations (e.g., map, filter)
❌ Avoid for small datasets (thread overhead > benefit).

Slide 4: Custom Thread Pools for Parallel Streams
Problem:
• By default, parallel streams use ForkJoinPool.commonPool() (shared across JVM).
• Can lead to resource contention in larger apps.
Solution: Use a custom ForkJoinPool
java
Copy
Download
ForkJoinPool customPool = new ForkJoinPool(4);
customPool.submit(() ->
numbers.parallelStream().map(n -> n * 2).forEach(System.out::println)
).get();
Note: Requires careful management to avoid leaks.

Slide 5: Introduction to CompletableFuture
Why CompletableFuture?
• Improves upon Future by allowing chaining, exception handling, and async composition.
Basic Example:
java
Copy
Download
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "Hello, World!";
});

future.thenAccept(System.out::println); // Prints when complete

Slide 6: Chaining Async Operations
Key Methods:
1. thenApply – Transform result.
2. thenAccept – Consume result (no return).
3. thenRun – Execute after completion.
Example:
java
Copy
Download
CompletableFuture.supplyAsync(() -> "Java")
.thenApply(s -> s + " Programming")
.thenAccept(System.out::println); // Prints "Java Programming"

Slide 7: Combining Futures
1. thenCombine (Merge two futures)
java
Copy
Download
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");

future1.thenCombine(future2, (s1, s2) -> s1 + " " + s2)
.thenAccept(System.out::println); // "Hello World"
2. allOf (Wait for all futures)
java
Copy
Download
CompletableFuture<Void> all = CompletableFuture.allOf(future1, future2);
all.thenRun(() -> System.out.println("All done!"));

Slide 8: Error Handling
1. exceptionally (Fallback value)
java
Copy
Download
CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) throw new RuntimeException("Error!");
return "Success";
}).exceptionally(ex -> "Fallback: " + ex.getMessage());
2. handle (Success + Error in one method)
java
Copy
Download
future.handle((res, ex) -> {
return ex != null ? "Error occurred" : res;
});

Slide 9: Timeouts & Cancellation
1. orTimeout (Timeout after delay)
java
Copy
Download
future.orTimeout(1, TimeUnit.SECONDS)
.exceptionally(ex -> "Timed out!");
2. completeOnTimeout (Fallback if timeout)
java
Copy
Download
future.completeOnTimeout("Default", 1, TimeUnit.SECONDS);

Slide 10: Best Practices
✔ Use parallel streams for CPU-bound tasks (not IO-bound).
✔ Prefer CompletableFuture over raw Thread for async tasks.
✔ Always handle exceptions in futures.
✔ Avoid blocking calls (get()) without timeouts.

Handout: Summary & Exercises
Key Takeaways:
• Parallel streams simplify concurrent processing but require large datasets.
• CompletableFuture enables powerful async workflows with chaining.
• Error handling (exceptionally, handle) is critical for robustness.
Exercises:
1. Convert a sequential stream to parallel and measure performance.
2. Chain 3 CompletableFuture operations (fetch data → process → save).
3. Simulate a timeout in CompletableFuture and provide a fallback.

Conclusion
Parallel streams and CompletableFuture make Java concurrency declarative and efficient.
Next Lecture: Concurrency Design Patterns (Actor Model, Reactive Programming)

Simple Example of Using Maps in Java
Here's a basic example demonstrating how to use the Map interface in Java, specifically with the HashMap implementation:
java
Copy
Download
import java.util.HashMap;
import java.util.Map;

public class MapExample {
public static void main(String[] args) {
// Create a Map (HashMap implementation)
Map<String, Integer> ageMap = new HashMap<>();

// Adding entries to the map
ageMap.put("Alice", 25);
ageMap.put("Bob", 30);
ageMap.put("Charlie", 28);

// Accessing values
System.out.println("Alice's age: " + ageMap.get("Alice"));

// Checking if a key exists
if (ageMap.containsKey("Bob")) {
System.out.println("Bob is in the map!");
}

// Iterating through the map
System.out.println("\nAll entries:");
for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// Removing an entry
ageMap.remove("Charlie");
System.out.println("\nAfter removing Charlie:");
System.out.println(ageMap);

// Size of the map
System.out.println("\nNumber of entries: " + ageMap.size());
}
}
Output:
Copy
Download
Alice's age: 25
Bob is in the map!

All entries:
Alice: 25
Bob: 30
Charlie: 28

After removing Charlie:
{Alice=25, Bob=30}

Number of entries: 2
Key Map Operations Demonstrated:
1. put(key, value) - Adds key-value pairs to the map
2. get(key) - Retrieves the value for a given key
3. containsKey(key) - Checks if a key exists
4. entrySet() - Gets all key-value pairs for iteration
5. remove(key) - Removes an entry by key
6. size() - Gets the number of entries
This example uses HashMap, but you could also use other implementations like TreeMap (for sorted order) or LinkedHashMap (for insertion-order preservation) with the same basic operations.

Simple Stream API Example in Java
Here's a basic example demonstrating Java's Stream API with common operations:
java
Copy
Download
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Anna", "Eve");

// Example 1: Filter names starting with 'A' and convert to uppercase
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.collect(Collectors.toList());

System.out.println("Names starting with 'A': " + filteredNames);

// Example 2: Calculate total length of all names
int totalLength = names.stream()
.mapToInt(String::length)
.sum();

System.out.println("Total length of all names: " + totalLength);

// Example 3: Find the longest name
names.stream()
.max((name1, name2) -> Integer.compare(name1.length(), name2.length()))
.ifPresent(longest -> System.out.println("Longest name: " + longest));

// Example 4: Process each element
System.out.println("All names in uppercase:");
names.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
Output:
Copy
Download
Names starting with 'A': [ALICE, ANNA]
Total length of all names: 25
Longest name: Charlie
All names in uppercase:
ALICE
BOB
CHARLIE
DAVID
ANNA
EVE
Key Stream Operations Demonstrated:
1. stream() - Creates a stream from a collection
2. filter() - Selects elements that match a predicate
3. map() - Transforms each element
4. collect() - Converts stream back to a collection
5. mapToInt() - Converts to a stream of primitives
6. sum() - Aggregates numeric values
7. max() - Finds the maximum element
8. forEach() - Performs an action on each element
This example shows the declarative style of programming with Streams, which is often more readable than traditional iterative approaches.

Lecture Slides & Handouts: Java Stream API
1. Title Slide
Topic: Java Stream API
Objective: Understand Streams, their operations, and how to use them for functional-style data processing.
Key Concepts: Stream Creation, Intermediate & Terminal Operations, Parallel Streams

2. Introduction to Stream API
What is a Stream?
• A sequence of elements supporting sequential/parallel operations.
• Not a data structure, but operates on collections, arrays, or I/O channels.
• Key Features:
◦ Lazy evaluation (only processed when needed).
◦ No storage (does not modify the source).
◦ Functional-style operations (filter, map, reduce).
Why Use Streams?
✔ Readability – Declarative style (what to do, not how).
✔ Parallelism – Easy multi-threading with parallelStream().
✔ Reusability – Chain operations efficiently.

3. Stream Pipeline
A stream pipeline consists of:
1. Source (Collection, Array, I/O)
2. Intermediate Operations (Transform data, return new streams)
◦ filter(), map(), sorted(), distinct(), limit()
3. Terminal Operation (Produce result/ side-effect)
◦ collect(), forEach(), reduce(), count(), min()/max()
Example:
java
Copy
Download
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squares = numbers.stream() // Source
.filter(n -> n % 2 == 0) // Intermediate
.map(n -> n * n) // Intermediate
.collect(Collectors.toList()); // Terminal
System.out.println(squares); // [4, 16]

4. Stream Creation
From Collections
java
Copy
Download
List<String> list = Arrays.asList("A", "B", "C");
Stream<String> stream = list.stream();
From Arrays
java
Copy
Download
String[] array = {"A", "B", "C"};
Stream<String> stream = Arrays.stream(array);
Using Stream.of()
java
Copy
Download
Stream<String> stream = Stream.of("A", "B", "C");
Infinite Streams
java
Copy
Download
Stream<Integer> infiniteNumbers = Stream.iterate(0, n -> n + 1);
Stream<Double> randomNumbers = Stream.generate(Math::random);

5. Intermediate Operations
Operation
Description
Example
filter(Predicate)
Selects elements matching condition
.filter(n -> n > 10)
map(Function)
Transforms each element
.map(String::toUpperCase)
sorted()
Sorts elements (natural/comparator)
.sorted(Comparator.reverseOrder())
distinct()
Removes duplicates
.distinct()
limit(n)
Truncates to first n elements
.limit(5)

6. Terminal Operations
Operation
Description
Example
collect()
Converts to Collection
.collect(Collectors.toList())
forEach()
Performs action on each
.forEach(System.out::println)
count()
Returns count
.count()
reduce()
Aggregates elements
.reduce(0, (a,b) -> a + b)
anyMatch()
Checks if any matches
.anyMatch(s -> s.contains("a"))

7. Parallel Streams
• Uses multi-threading for faster processing.
• Example:
java
Copy
Download
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
int sum = numbers.parallelStream()
.mapToInt(n -> n)
.sum();
System.out.println(sum); // 15
⚠ Caution: Not always faster (thread overhead). Use for large datasets.

8. Hands-on Exercises (Handout)
Exercise 1: Filter & Map
Given a list of names: ["Alice", "Bob", "Anna", "Tom"]
• Filter names starting with "A".
• Convert them to uppercase.
Exercise 2: Reduce & Sum
Given List<Integer> numbers = List.of(1, 2, 3, 4, 5);
• Find the sum of even numbers.
• Find the maximum number.
Exercise 3: Collectors
Convert a list of strings into:
• A single comma-separated string.
• A map where key = name, value = length.

9. Summary
✔ Streams process data declaratively.
✔ Intermediate ops (filter, map) transform data.
✔ Terminal ops (collect, reduce) produce results.
✔ Parallel streams improve performance for large datasets.

10. References & Further Reading
• Oracle Stream Docs
• Book: "Java 8 in Action" (Raoul-Gabriel Urma)

Lecture Slides & Handouts: Java Collections Framework
1. Title Slide
Topic: Java Collections Framework
Objective: Understand core collection interfaces, implementations, and their use cases.
Key Concepts: List, Set, Map, Iterators, Comparators, Thread Safety

2. Introduction to Collections
What is a Collection?
• A container that groups multiple elements into a single unit.
• Key Interfaces:
◦ Collection (Root) → List, Set, Queue
◦ Map (Separate hierarchy)
Why Use Collections?
✔ Dynamic Sizing – Grow/shrink as needed.
✔ Performance – Optimized data structures (e.g., ArrayList, HashMap).
✔ Utility Methods – Sorting, searching, shuffling (Collections class).

3. Core Interfaces & Implementations
Interface
Description
Implementations
List
Ordered, allows duplicates
ArrayList, LinkedList, Vector
Set
Unique elements
HashSet, LinkedHashSet, TreeSet
Queue
FIFO/LIFO order
LinkedList, PriorityQueue
Map
Key-value pairs
HashMap, LinkedHashMap, TreeMap
Example: List vs. Set
java
Copy
Download
List<String> list = new ArrayList<>();
list.add("A"); list.add("A"); // Allows duplicates
Set<String> set = new HashSet<>();
set.add("A"); set.add("A"); // Only one "A" stored

4. Common Operations
List Operations
java
Copy
Download
List<String> fruits = new ArrayList<>();
fruits.add("Apple"); // Add
fruits.get(0); // Access
fruits.remove("Apple"); // Remove
fruits.contains("Apple"); // Search
Map Operations
java
Copy
Download
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 25); // Insert
map.get("Alice"); // Retrieve
map.containsKey("Alice"); // Check key
map.keySet(); // Get all keys

5. Iterating Over Collections
Using Iterator
java
Copy
Download
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Enhanced For-Loop
java
Copy
Download
for (String fruit : fruits) {
System.out.println(fruit);
}
forEach (Java 8+)
java
Copy
Download
fruits.forEach(System.out::println);
map.forEach((k, v) -> System.out.println(k + ": " + v));

6. Sorting & Comparators
Natural Order (Comparable)
java
Copy
Download
List<String> names = Arrays.asList("Bob", "Alice");
Collections.sort(names); // ["Alice", "Bob"]
Custom Order (Comparator)
java
Copy
Download
Collections.sort(names, (a, b) -> b.compareTo(a)); // ["Bob", "Alice"]
names.sort(Comparator.reverseOrder());
TreeSet/TreeMap (Auto-Sorted)
java
Copy
Download
Set<Integer> sortedSet = new TreeSet<>();
sortedSet.add(3); sortedSet.add(1); // [1, 3]

7. Thread-Safe Collections
Class
Description
Alternative (Java 5+)
Vector
Synchronized ArrayList
Collections.synchronizedList()
Hashtable
Synchronized HashMap
ConcurrentHashMap
Stack
Synchronized LIFO
ArrayDeque
Example: ConcurrentHashMap
java
Copy
Download
Map<String, Integer> safeMap = new ConcurrentHashMap<>();
safeMap.put("Alice", 25); // Thread-safe

8. Hands-on Exercises (Handout)
Exercise 1: List Operations
1. Create an ArrayList of integers.
2. Remove all odd numbers.
3. Sort in descending order.
Exercise 2: Map Manipulation
1. Given a Map<String, Integer>, find the key with the highest value.
2. Invert the map (swap keys/values).
Exercise 3: Custom Sorting
Sort a List<Employee> by:
1. Name (alphabetical).
2. Salary (descending).

9. Summary
✔ Lists: Ordered, indexed, allows duplicates.
✔ Sets: Unique elements, fast lookup.
✔ Maps: Key-value pairs, no duplicate keys.
✔ Thread Safety: Use ConcurrentHashMap or synchronized wrappers.

10. References & Further Reading
• Oracle Collections Guide
• Book: "Effective Java" (Joshua Bloch)

Handout Download Link (Optional)
📥 Download PDF Exercises & Solutions

Need more? Ask for:
• Real-world use cases (e.g., caching with HashMap).
• Performance benchmarks (ArrayList vs. LinkedList).
• Advanced topics (e.g., WeakHashMap, EnumSet). 🚀

Real-World Use Cases for HashMap in Java
HashMap is one of the most widely used data structures in Java due to its O(1) average-time complexity for get() and put() operations. Below are practical real-world scenarios where HashMap shines:

1. Caching (In-Memory Key-Value Store)
Use Case:
• Store frequently accessed data (like user sessions, API responses) to avoid repeated computations or database calls.
Example:
java
Copy
Download
Map<String, User> userCache = new HashMap<>();

public User getUserById(String userId) {
if (userCache.containsKey(userId)) {
return userCache.get(userId); // Fast lookup
} else {
User user = fetchUserFromDatabase(userId); // Expensive operation
userCache.put(userId, user); // Cache for future
return user;
}
}
✔ Pros:
• Reduces database load.
• Speeds up repeated access.
⚠ Limitation:
• Not thread-safe (use ConcurrentHashMap in multi-threaded apps).

2. Frequency Counting (Word/Character Count)
Use Case:
• Count occurrences of words in a document or characters in a string.
Example:
java
Copy
Download
String text = "hello world hello";
Map<String, Integer> wordCount = new HashMap<>();

for (String word : text.split(" ")) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
// Output: {hello=2, world=1}
✔ Pros:
• Efficient for large datasets.
• Easy to extend (e.g., find most frequent word).

3. Database Indexing (Simulating a Lookup Table)
Use Case:
• Store primary keys (e.g., userId) mapped to objects for fast retrieval.
Example:
java
Copy
Download
Map<Long, Product> productIndex = new HashMap<>();
List<Product> products = fetchProductsFromDB();

for (Product p : products) {
productIndex.put(p.getId(), p); // O(1) access later
}

// Later, fetch instantly:
Product p = productIndex.get(123L); // No DB query needed
✔ Pros:
• Avoids full database scans.
• Optimizes performance in read-heavy apps.

4. URL Shortener (Slug → Original URL Mapping)
Use Case:
• Services like Bit.ly store short codes (abc123) mapped to full URLs (https://example.com/very-long-url).
Example:
java
Copy
Download
Map<String, String> urlMap = new HashMap<>();

// Store shortened URL
urlMap.put("abc123", "https://example.com/very-long-url";);

// Retrieve original URL
String originalUrl = urlMap.get("abc123"); // Returns full URL
✔ Pros:
• Instant lookup for redirects.
• Low memory overhead.

5. Memoization (Optimizing Recursive Algorithms)
Use Case:
• Cache results of expensive function calls (e.g., Fibonacci, factorial).
Example:
java
Copy
Download
Map<Integer, Long> memo = new HashMap<>();

public long fibonacci(int n) {
if (n <= 1) return n;
if (memo.containsKey(n)) return memo.get(n); // Return cached value

long fib = fibonacci(n - 1) + fibonacci(n - 2);
memo.put(n, fib); // Store result
return fib;
}
✔ Pros:
• Reduces time complexity from O(2ⁿ) to O(n).

6. User Session Management (Web Applications)
Use Case:
• Track logged-in users with a session ID → User mapping.
Example:
java
Copy
Download
Map<String, Session> activeSessions = new HashMap<>();

// On login:
String sessionId = generateSessionId();
activeSessions.put(sessionId, new Session(user));

// On request:
Session session = activeSessions.get(sessionId);
if (session != null) {
// User is authenticated
}
✔ Pros:
• Faster than querying a database on every request.
⚠ Limitation:
• Not persistent (use Redis for distributed systems).

7. Phonebook/Contact List (Name → Phone Number)
Use Case:
• Store and retrieve contact details efficiently.
Example:
java
Copy
Download
Map<String, String> phonebook = new HashMap<>();
phonebook.put("Alice", "+1234567890");
phonebook.put("Bob", "+0987654321");

// Get Bob's number:
String bobsNumber = phonebook.get("Bob");
✔ Pros:
• Faster than searching a List linearly.

When NOT to Use HashMap?
❌ If you need:
1. Ordering → Use LinkedHashMap (insertion order) or TreeMap (sorted order).
2. Thread Safety → Use ConcurrentHashMap.
3. Duplicate Keys → Not possible (keys must be unique).

Summary
Use Case
Example
Benefit
Caching
User session store
Avoid repeated computations
Frequency Counting
Word/character counter
Efficient aggregation
Database Indexing
Primary key → Object mapping
Fast lookups
URL Shortener
Short code → Long URL
Instant redirects
Memoization
Fibonacci caching
Optimizes recursion
Session Management
Session ID → User data
Quick authentication

F…

Схожі кандидати

Усі схожі кандидати

Кандидати за містами