Recap 06062025
Recap 06062025
Thread-safe No Yes
No (manually synchronized if
Synchronized Internally synchronized
needed)
Example HashMap:
package day4.collectionmap;
import java.util.HashMap;
import java.util.Map;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
t1.start();
t2.start();
t1.join();
6/6/2025 1
t2.join();
Example ConcurrentHashMap:
package day4.collectionmap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
t1.start();
t2.start();
t1.join();
6/6/2025 2
t2.join();
Result:
package day4.collectionmap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
6/6/2025 3
3.12. Thread
Demo ways to create thread:
package day4.thread;
import java.util.concurrent.TimeUnit;
6/6/2025 4
try {
TimeUnit.MILLISECONDS.sleep(250);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread2 = new Thread(myRunnable);
//print 2:
thread2.start();
}
}
System.out.println(t.getState()); // NEW
t.start();
System.out.println(t.getState()); // RUNNABLE
Thread.sleep(100); // give time for thread to enter sleep
System.out.println(t.getState()); // TIMED_WAITING
t.join();
System.out.println(t.getState()); // TERMINATED
}
}
Thread states
6/6/2025 5
1. NEW
Created using new Thread(...) , but not yet started.
2. RUNNABLE
Thread is either running or ready to run (depends on CPU availability).
3. BLOCKED
Waiting to acquire a lock (monitor) to enter a synchronized block/method.
4. WAITING
Thread is waiting indefinitely for another thread's action (no timeout).
Object.wait()
Thread.join()
LockSupport.park()
5. TIMED_WAITING
Thread waits for a specific time before becoming RUNNABLE again.
Common methods:
Thread.sleep(ms)
6/6/2025 6
join(ms)
wait(ms)
LockSupport.parkNanos()
6. TERMINATED
Thread has completed or was stopped with an uncaught exception.
if (!t.isAlive()) {
System.out.println("Thread terminated");
}
System.out.println(t.getState()); // NEW
t.start();
System.out.println(t.getState()); // RUNNABLE
Thread.sleep(100); // give time for thread to enter sleep
System.out.println(t.getState()); // TIMED_WAITING
t.join();
System.out.println(t.getState()); // TERMINATED
}
}
6/6/2025 7
A self-contained unit of
A lightweight unit of execution
Definition execution with its own memory
within a process
space
Communication between
Threads easily share data via
Communication processes is complex (IPC:
shared memory
pipes, sockets, etc.)
2 or more threads access shared resource at the same time, and at least one thread modifies it.
→ unexpected behavior or corrupt data
2. Deadlocks
2 or more threads are waiting on each other to release locks, but none ever proceed.
3. Starvation
A thread never gets CPU time or access to resources because others dominate.
1 thread updates a shared variable, but another thread doesn’t see the change due to caching
or reordering
Exercise on thread:
package day4.thread;
import java.util.Random;
class Horse implements Runnable {
6/6/2025 8
this.id = id;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(500); // wait 0.5 second
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
6/6/2025 9
3.14. Reflection
Reflection:
package day4.reflection;
import java.util.Arrays;
import java.util.List;
// Export
CsvExporter.exportToCsv(people, filePath);
6/6/2025 10
// Import
List<Student> imported = CsvImporter.importFromCsv(filePath, Student.class);
package day4.reflection;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
public static void exportToCsv(List<?> objects, String filePath) throws IOException, IllegalAcces
if (objects == null || objects.isEmpty()) return;
// Data rows
for (Object obj : objects) {
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);
Object value = fields[i].get(obj);
writer.append(value != null ? value.toString() : "");
if (i < fields.length - 1) writer.append(",");
}
writer.append("\n");
}
}
}
}
package day4.reflection;
6/6/2025 11
import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public static <T> List<T> importFromCsv(String filePath, Class<T> clazz) throws Exception {
List<T> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String headerLine = br.readLine(); // skip headers
if (headerLine == null) return list;
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
T instance = clazz.getDeclaredConstructor().newInstance();
list.add(instance);
}
}
return list;
}
package day4.reflection;
6/6/2025 12
private int age;
private String email;
Result:
6/6/2025 13
6/6/2025 14