Java
Creating traditional Threads
There are multiple ways to create threads
- Implementing a Runnable Interface
- Extend Thread class
- Implement Callable Interface
- Use Executer Framework/Thread Pool
- Reactive Programming: e.g. SpringWebFlux
Virtual Threads
A lightweight threading model (Project Loom). They allow you to create many concurrent threads efficiently. Introduced in Java 21.
- Managed by the JVM, not the OS.
- Scheduled by the Java runtime, not the operating system kernel.
- Each virtual thread runs on a carrier platform thread, but the JVM can suspend and resume them as needed.
When to use
- Concurrent I/O-bound tasks (e.g., handling many HTTP requests).
- As a drop-in replacement for traditional thread where you need numerous concurrent tasks.
- Simplifying asynchronous code by writing it in a synchronous style.
How to use
Runnable
java
Runnable task = () -> {
System.out.println("Running in: " + Thread.currentThread());
};
Thread.startVirtualThread(task);
Thread
java
Thread t = Thread.ofVirtual().start(() -> {
System.out.println("Virtual thread says hi!");
});
Executor service
java
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> {
System.out.println("Hello from a virtual thread!");
});
}
Difference between ClassNotFound ans NoClassDefFound Exception
ClassNotFound
A RuntimeException while loading a class with Class.forName or loadClass. It's a checked Exception
NoClassDefFound
Class exists while compiling, but not present to runtime It's an Error
Records
A record is a compact syntax for declaring classes. They are pure data classes. It helps to reduce boilerplate code. Introduced in Java 16.
Key Characteristics
- Immutable: Fields are final and set only once via the constructor.
- Reduces boilerplate by generating:
- Constructor
- Getters (named exactly like the field names)
- equals(), hashCode(), toString()
- Final: Records are implicitly final and cannot be extended.
Limitations
- Can't extend other classes.
- Can't define mutable fields.
Example
java
public record Guest(String name, int age) {}
Pattern matching for instanceof
With pattern matching for instanceof, Java combines the type check and the cast into one step. Introduced in Java 16.
Example
java
if (obj instanceof String s) {
System.out.println(s.length()); // no need to cast
}
instead of (pre Java 16)
java
if (obj instanceof String) {
String s = (String) obj; // explicit cast
System.out.println(s.length());
}
Can be used in the same expression
java
if (obj instanceof String s && s.length() > 3) {
System.out.println("Long string: " + s);
}