JDK 21 features | code2java

JDK 21 Features

πŸ“š Table of Contents

  • What is JDK 21
  • Why JDK 21 Matters
  • Virtual Threads (Project Loom)
  • Structured Concurrency
  • Scoped Values
  • Pattern Matching for Switch (Final)
  • Record Patterns
  • Sequenced Collections
  • String Templates (Preview)
  • Summary
  • Interview Questions

πŸ€” What is JDK 21?

JDK 21 is a Long-Term Support (LTS) release of Java.

πŸ‘‰ That means:

  • It will be supported for years
  • Production-ready features
  • Major improvements in concurrency and language design

πŸ’‘ Why JDK 21 is Important

Before JDK 21:

⚠️ Threads were expensive
⚠️ Async code was complex (CompletableFuture hell πŸ˜…)
⚠️ Pattern matching was limited

JDK 21 fixes these problems in a very elegant way.


🧡 1. Virtual Threads (Project Loom)

This is the biggest feature.

πŸ‘‰ Problem

Traditional threads (platform threads):

  • Heavyweight
  • Limited (~thousands max)
  • Expensive context switching

πŸ‘‰ Solution

Virtual Threads:

  • Lightweight
  • Managed by JVM, not OS
  • You can create millions of them

🧠 Internal Working

πŸ‘‰ Virtual threads are scheduled by the JVM using carrier threads (actual OS threads)

Think of it like:

  • Many virtual threads β†’ mapped onto few OS threads
  • JVM handles scheduling instead of OS

βœ… Example

public class VirtualThreadExample {
    public static void main(String[] args) throws Exception {

        Runnable task = () -> {
            System.out.println("Running in: " + Thread.currentThread());
        };

        Thread.startVirtualThread(task);

        Thread.sleep(1000);
    }
}

πŸ‘‰ Output shows something like:

VirtualThread[#21]/runnable@ForkJoinPool

πŸ”₯ Real Use Case

Handling thousands of API calls:

try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {

    for (int i = 0; i < 10000; i++) {
        executor.submit(() -> {
            System.out.println("Task executed by: " + Thread.currentThread());
        });
    }
}

πŸ’‘ No more thread pool tuning headache.


🧡 2. Structured Concurrency (Preview)

This feature changes how we manage parallel tasks.

πŸ‘‰ Problem

When multiple threads run:

  • Hard to manage lifecycle
  • Error handling becomes messy

πŸ‘‰ Solution

Structured Concurrency groups tasks together.

🧠 Internal Idea

πŸ‘‰ Treat multiple threads like a single unit of work

If one fails:

  • Cancel others
  • Propagate error cleanly

βœ… Example

import java.util.concurrent.*;

public class StructuredConcurrencyExample {

    public static void main(String[] args) throws Exception {

        try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {

            Future<String> task1 = scope.fork(() -> "Result 1");
            Future<String> task2 = scope.fork(() -> "Result 2");

            scope.join();  
            scope.throwIfFailed();

            System.out.println(task1.resultNow());
            System.out.println(task2.resultNow());
        }
    }
}

πŸ’‘ Cleaner than CompletableFuture chains.


πŸ” 3. Scoped Values (Preview)

πŸ‘‰ Problem

ThreadLocal:

  • Hard to manage
  • Memory leaks risk
  • Debugging nightmare

πŸ‘‰ Solution

Scoped Values provide immutable thread-bound data

🧠 Internal Concept

πŸ‘‰ Values are:

  • Immutable
  • Bound to execution scope
  • Automatically cleaned

βœ… Example

import java.lang.ScopedValue;

public class ScopedValueExample {

    static final ScopedValue<String> USER = ScopedValue.newInstance();

    public static void main(String[] args) {

        ScopedValue.where(USER, "Amit").run(() -> {
            System.out.println(USER.get());
        });
    }
}

πŸ’‘ Much safer than ThreadLocal.


πŸ”„ 4. Pattern Matching for Switch (Final)

Finally stable πŸŽ‰

πŸ‘‰ Before

if (obj instanceof String) {
    String s = (String) obj;
}

πŸ‘‰ Now

static void test(Object obj) {
    switch (obj) {
        case String s -> System.out.println("String: " + s);
        case Integer i -> System.out.println("Integer: " + i);
        default -> System.out.println("Unknown");
    }
}

🧠 Internal Benefit

πŸ‘‰ Compiler ensures:

  • Exhaustiveness
  • Type safety
  • Less casting

πŸ“¦ 5. Record Patterns

Records become even more powerful.

βœ… Example

record Person(String name, int age) {}

public class RecordPatternExample {

    static void print(Object obj) {
        if (obj instanceof Person(String name, int age)) {
            System.out.println(name + " is " + age);
        }
    }
}

πŸ’‘ Direct destructuring of objects.


πŸ“š 6. Sequenced Collections

Finally, Java standardizes order-aware collections.

πŸ‘‰ New Interfaces

  • SequencedCollection
  • SequencedSet
  • SequencedMap

βœ… Example

import java.util.*;

public class SequencedExample {
    public static void main(String[] args) {

        SequencedCollection<String> list = new ArrayList<>();

        list.add("A");
        list.add("B");

        System.out.println(list.getFirst());
        System.out.println(list.getLast());
    }
}

🧠 Why It Matters

πŸ‘‰ Before:

  • No consistent way to access first/last

πŸ‘‰ Now:

  • Unified API across collections

πŸ§ͺ 7. String Templates (Preview)

Safer and cleaner string building.

πŸ‘‰ Problem

String query = "SELECT * FROM users WHERE id = " + userId;

⚠️ Risk of injection

String name = "John";
String message = STR."Hello \{name}";

🧠 Internal Idea

πŸ‘‰ Template processors validate and transform strings safely.


βœ… Summary

JDK 21 is not just an upgrade β€” it’s a shift.

πŸ‘‰ Key takeaways:

  • Virtual Threads β†’ Massive scalability
  • Structured Concurrency β†’ Cleaner parallel code
  • Scoped Values β†’ Safer context handling
  • Pattern Matching β†’ Better readability
  • Record Patterns β†’ Simpler data handling
  • Sequenced Collections β†’ Consistent APIs
  • String Templates β†’ Safer string operations

🎯 Interview Questions

1. What are Virtual Threads?

πŸ‘‰ Lightweight threads managed by JVM for high scalability.

2. Difference between Virtual Thread and Platform Thread?

πŸ‘‰ Virtual β†’ JVM managed
πŸ‘‰ Platform β†’ OS managed

3. What is Structured Concurrency?

πŸ‘‰ Managing multiple tasks as a single unit.

4. Why Scoped Values over ThreadLocal?

πŸ‘‰ Immutable, safer, no memory leaks.

5. What is Pattern Matching in switch?

πŸ‘‰ Type-based branching with automatic casting.

6. What are Record Patterns?

πŸ‘‰ Destructuring objects directly in conditions.

7. What are Sequenced Collections?

πŸ‘‰ Collections with defined ordering operations.

Related Posts

  • Abstract Class In JAVA

    Hello Friends, This tutorial is for all the Java followers. One of the best feature that is widely used is the term ‘Abstract’. This term can be used as either class or a simple method. An abstract method is any method that is just declared but not instantiated. In other words one can just create…

  • Threads in Java.

    Hello Friends, This is the tutorial for the java developers. One of the most significance feature of core java is Threading. Threading deals with the processing of Threads in a single java program. Let us learn what actually are Threads. *What are Threads? Threads are independently running processes that are isolated from each other upto…

  • Collections In Java.

    Hello friends, Welcome to another tutorial for java followers. You all may have heard about Collections, it is one of the amazing feature in java. Collections are the object for the group of elements, these elements are nothing but the different data structures like as Array Lists, Linked Lists, Vectors, Hash tables,Hash List, Trees, Hash…

  • Java Date Format.

    Hello Friends, This is one of my tutorials regarding java Date format / object in Java. Many of us find it difficult to store the current date from the java application in database. Lets consider MySql as a database in this case. Now when we create a row in the database table that stores date…

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.