Extremely Serious

Month: September 2025

Java 25 Compact Source Files: A New Simplicity with Instance Main Methods

Java continues evolving to meet the needs of developers—from beginners learning the language to pros writing quick scripts. Java 25 introduces Compact Source Files, a feature that lets you write Java programs without explicit class declarations, coupled with Instance Main Methods which allow entry points that are instance-based rather than static. This combination significantly reduces boilerplate, simplifies small programs, and makes Java more approachable while preserving its power and safety.

What Are Compact Source Files?

Traditionally, a Java program requires a class and a public static void main(String[] args) method. However, this requirement adds ceremony that can be cumbersome for tiny programs or for learners.

Compact source files lift this restriction by implicitly defining a final top-level class behind the scenes to hold fields and methods declared outside any class. This class:

  • Is unnamed and exists in the unnamed package.
  • Has a default constructor.
  • Extends java.lang.Object and implements no interfaces.
  • Must contain a launchable main method, which can be an instance method (not necessarily static).
  • Cannot be referenced by name in the source.

This means a full Java program can be as simple as:

void main() {
    IO.println("Hello, World!");
}

The new java.lang.IO class introduced in Java 25 provides simple convenient methods for console output like IO.println().

Implicit Imports for Compact Source Files

To keep programs concise, compact source files automatically import all public top-level classes and interfaces exported by the java.base module. This includes key packages such as java.util, java.io, java.math, and java.lang. So classes like List or BigDecimal are immediately available without import declarations.

Modules outside java.base require explicit import declarations.

Limitations and Constraints

Compact source files have some structural constraints:

  • The implicit class cannot be named or explicitly instantiated.
  • No package declarations are allowed; the class is always in the unnamed package.
  • Static members cannot be referenced via method references.
  • The IO class’s static methods require qualification.
  • Complex multi-class or modular programs should evolve into regular class-based files with explicit imports and package declarations.

This feature targets small programs, scripts, and educational use while preserving Java’s rigorous type safety and tooling compatibility.

Using Command-Line Arguments in a Compact Source File

Compact source files support standard command-line arguments passed to the main method as a String[] parameter, just like traditional Java programs.

Here is an example that prints provided command-line arguments:

void main(String[] args) {
    if (args.length == 0) {
        IO.println("No arguments provided.");
        return;
    }
    IO.println("Arguments:");
    for (var arg : args) {
        IO.println(" - " + arg);
    }
}

Save this as PrintArgs.java, then run it with:

java PrintArgs.java apple banana cherry

Output:

textArguments:
 - apple
 - banana
 - cherry

This shows how you can easily handle inputs in a script-like manner without boilerplate class syntax.

Growing Your Program

If your program outgrows simplicity, converting from a compact source file to a named class is straightforward. Wrap methods and fields in a class declaration and add imports explicitly. For instance:

import module java.base;

class PrintArgs {
    void main(String[] args) {
        if (args.length == 0) {
            IO.println("No arguments provided.");
            return;
        }
        IO.println("Arguments:");
        for (var arg : args) {
            IO.println(" - " + arg);
        }
    }
}

The logic inside main remains unchanged, enabling an easy migration path.

Conclusion

Java 25’s compact source files paired with instance main methods introduce a fresh, lightweight way to write Java programs. By reducing ceremony and automatically importing core APIs, they enable rapid scripting, teaching, and prototyping, while maintaining seamless interoperability with the full Java platform. Handling command-line arguments naturally fits into this new model, encouraging exploration and productivity in a familiar yet simplified environment.

This innovation invites developers to write less, do more, and enjoy Java’s expressive power with less friction.

Scoped Values in Java 25: Definitive Context Propagation for Modern Java

With the release of Java 25, scoped values come out of preview and enter the mainstream as one of the most impactful improvements for concurrency and context propagation in Java’s recent history. Designed to address the perennial issue of safely sharing context across method chains and threads, scoped values deliver a clean, immutable, and automatically bounded solution that dethrones the error-prone ThreadLocal for most scenarios.

Rethinking Context: Why Scoped Values?

For years, Java developers have used ThreadLocal to pass data down a call stack—such as security credentials, logging metadata, or request-specific state. While functional, ThreadLocal suffers from lifecycle ambiguity, memory leaks, and incompatibility with lightweight virtual threads. Scoped values solve these problems by making context propagation explicit in syntax, immutable in nature, and automatic in cleanup.

The Mental Model

Imagine code execution as moving through a series of rooms, each with its unique lighting. A scoped value is like setting the lighting for a room—within its boundaries, everyone sees the same illumination (data value), but outside those walls, the setting is gone. Each scope block clearly defines where the data is available and safe to access.

How Scoped Values Work

Scoped values require two ingredients:

  • Declaration: Define a ScopedValue as a static final field, usually parameterized by the intended type.
  • Binding: Use ScopedValue.where() to create an execution scope where the value is accessible.

Inside any method called within the binding scope—even dozens of frames deep—the value can be retrieved by .get(), without explicit parameter passing.

Example: Propagating User Context Across Methods

// Declare the scoped value
private static final ScopedValue<String> USERNAME = ScopedValue.newInstance();

public static void main(String[] args) {
    ScopedValue.where(USERNAME, "alice").run(() -> entryPoint());
}

static void entryPoint() {
    printCurrentUser();
}

static void printCurrentUser() {
    System.out.println("Current user: " + USERNAME.get()); // Outputs "alice"
}

In this sample, USERNAME is accessible in any method within the binding scope, regardless of how far it’s called from the entry point.

Nested Binding and Rebinding

Scoped values provide nested rebinding: within a scope, a method can establish a new nested binding for the same value, which is then available only to its callees. This ensures truly bounded context lifetimes and avoids unintended leakage or overwrites.

// Declare the scoped value
private static final ScopedValue<String> MESSAGE = ScopedValue.newInstance();

void foo() {
    ScopedValue.where(MESSAGE, "hello").run(() -> bar());
}

void bar() {
    System.out.println(MESSAGE.get()); // prints "hello"
    ScopedValue.where(MESSAGE, "goodbye").run(() -> baz());
    System.out.println(MESSAGE.get()); // prints "hello"
}

void baz() {
    System.out.println(MESSAGE.get()); // prints "goodbye"
}

Here, the value "goodbye" is only visible within the nested scope inside baz, while "hello" remains for bar outside that sub-scope.openjdk

Thread Safety and Structured Concurrency

Perhaps the biggest leap: scoped values are designed for modern concurrency, including Project Loom’s virtual threads and Java's structured concurrency. Scoped values are automatically inherited by child threads launched within the scope, eliminating complex thread plumbing and ensuring correct context propagation.

// Declare the scoped value
private static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();

public static void main(String[] args) throws InterruptedException {
    String requestId = "req-789";
    usingVirtualThreads(requestId);
    usingStructuredConcurrency(requestId);
}

private static void usingVirtualThreads(String requestId) {
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        // Launch multiple concurrent virtual threads, each with its own scoped value binding
        Future<?> taskA = executor.submit(() ->
                ScopedValue.where(REQUEST_ID, requestId).run(() -> processTask("Task VT A"))
        );
        Future<?> taskB = executor.submit(() ->
                ScopedValue.where(REQUEST_ID, requestId).run(() -> processTask("Task VT B"))
        );
        Future<?> taskC = executor.submit(() ->
                ScopedValue.where(REQUEST_ID, requestId).run(() -> processTask("Task VT C"))
        );

        // Wait for all tasks to complete
        try {
            taskA.get();
            taskB.get();
            taskC.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

private static void usingStructuredConcurrency(String requestId) {
    ScopedValue.where(REQUEST_ID, requestId).run(() -> {
        try (var scope = StructuredTaskScope.open()) {
            // Launch multiple concurrent virtual threads
            scope.fork(() -> {
                processTask("Task SC A");
            });
            scope.fork(() -> {
                processTask("Task SC B");
            });
            scope.fork(() -> {
                processTask("Task SC C");
            });

            scope.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
    });
}

private static void processTask(String taskName) {
    // Scoped value REQUEST_ID is automatically visible here
    System.out.println(taskName + " processing request: " + REQUEST_ID.get());
}

No need for explicit context passing—child threads see the intended value automatically.

Key Features and Advantages

  • Immutability: Values cannot be mutated within scope, preventing accidental overwrite and race conditions.
  • Automatic Cleanup: Context disappears at the end of the scope, eliminating leaks.
  • No Boilerplate: No more manual parameter threading across dozens of method signatures.
  • Designed for Virtual Threads: Plays perfectly with Java’s latest concurrency primitives.baeldung+2

Use Cases

  • Securely propagate authenticated user or tracing info in web servers.
  • Pass tenant, locale, metrics, or logger context across libraries.
  • Enable robust structured concurrency with context auto-inheritance.

Mastering Asynchronous Programming in Java with CompletableFuture and Virtual Threads

Java's CompletableFuture provides a powerful and flexible framework for asynchronous programming. Introduced in Java 8, it allows writing non-blocking, event-driven applications with simple and readable code. With Java 21 and Project Loom, virtual threads can be combined with CompletableFutures to achieve highly scalable concurrency with minimal overhead. This article explores the core usage patterns of CompletableFuture and how to leverage virtual threads effectively.

Basics of CompletableFuture Usage

At its simplest, a CompletableFuture represents a future result of an asynchronous computation. You can create one that runs asynchronously using the supplyAsync() or runAsync() methods.

  • supplyAsync() runs a background task that returns a result.
  • runAsync() runs a background task with no returned result.

Example:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World");
System.out.println(future.get());  // Blocks until the result is ready

In this example, the supplier runs asynchronously, and the main thread waits for its result using get(). The computation executes in the common ForkJoinPool by default.

Chaining and Composing Tasks

CompletableFuture excels at composing asynchronous tasks without nested callbacks:

  • thenApply() transforms the result of a completed future.
  • thenAccept() consumes the result without returning anything.
  • thenRun() runs a task once the future is complete.
  • thenCombine() combines results of two independent futures.
  • thenCompose() chains dependent futures for sequential asynchronous steps.

Example of chaining:

CompletableFuture.supplyAsync(() -> 10)
    .thenApply(result -> result + 20)
    .thenAccept(result -> System.out.println("Result: " + result));

Example of combining:

CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> 20);
CompletableFuture<Integer> combined = f1.thenCombine(f2, Integer::sum);
System.out.println(combined.get());  // 30

These patterns allow building complex, non-blocking workflows with clean and expressive code.

Exception Handling

CompletableFuture allows robust error handling without complicating the flow:

  • Use exceptionally() to recover with a default value on error.
  • Use handle() to process outcome result or exception.
  • Use whenComplete() to perform an action regardless of success or failure.

Example:

CompletableFuture.supplyAsync(() -> {
    if (true) throw new RuntimeException("Failure");
    return "Success";
}).exceptionally(ex -> "Recovered from " + ex.getMessage())
  .thenAccept(System.out::println);  // Outputs: Recovered from java.lang.RuntimeException: Failure

Waiting for Multiple Futures

The allOf() method is used to wait for multiple CompletableFutures to finish:

List<CompletableFuture<String>> futures = List.of(
    CompletableFuture.completedFuture("A"),
    CompletableFuture.completedFuture("B"),
    CompletableFuture.completedFuture("C"));

CompletableFuture<Void> allDone = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
allDone.join();  // Wait until all futures complete

This enables executing parallel asynchronous operations efficiently.

Using CompletableFuture with Virtual Threads

Java 21 introduces virtual threads, lightweight threads that allow massive concurrency with minimal resource consumption. To use CompletableFutures on virtual threads, create an executor backed by virtual threads and pass it to async methods.

Example:

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
        System.out.println("Running in virtual thread: " + Thread.currentThread());
        try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        System.out.println("Task completed");
    }, executor);

    future.join();
}
  • The executor is created with Executors.newVirtualThreadPerTaskExecutor().
  • Async tasks run on virtual threads, offering high scalability.
  • The executor must be closed to release resources and stop accepting tasks; using try-with-resources is recommended.

All operations such as thenApplyAsync() or thenCombineAsync() can similarly take the virtual thread executor to keep subsequent stages on virtual threads.

Summary

  • CompletableFuture allows flexible, readable asynchronous programming.
  • Tasks can be created, chained, combined, and composed easily.
  • Robust exception handling is built-in.
  • allOf() allows waiting on multiple futures.
  • With virtual threads, CompletableFuture scales brilliantly by offloading async tasks to lightweight threads.
  • Always close virtual thread executors to properly release resources.

Using CompletableFuture with virtual threads simplifies asynchronous programming and enables writing performant scalable Java applications with clean and maintainable code.

Exploring Java Non-Denotable Types

Java's evolving type system has brought powerful features like local variable type inference and lambda expressions — providing concise and expressive coding patterns. One nuanced concept that arises in this landscape is the idea of non-denotable types, which plays a subtle but important role in how type inference works and enables interesting use cases such as mutable state within lambdas without atomic types.

What Are Non-Denotable Types in Java?

Java programmers are familiar with declaring variables with explicit types like int, String, or class names. These are called denotable types — types you can write explicitly in your source code.

However, the Java compiler also works with non-denotable types behind the scenes:

  • These types cannot be explicitly named or expressed in Java source code.

  • Common examples include:

    • Anonymous class types: Each anonymous class has a unique generated subclass type.

    Example:

    var obj = new Runnable() {
        public void run() { System.out.println("Running..."); }
        public void runTwice() { run(); run(); }
    };
    obj.runTwice(); // This works because obj's type is the anonymous class, not just Runnable
    • Capture types: Types arising from generics with wildcards and the capture conversion process.
    import java.util.List;
    
    public class CaptureType {
    
        public static void main(String[] args) {
            List<?> unknownList = List.of("A", "B", "C");
    
            // Wildcard capture example: helper method with captured type
            printFirstElement(unknownList);
        }
    
        static <T> void printFirstElement(List<T> list) {
            if (!list.isEmpty()) {
                // 'T' here is the capture of '?'
                System.out.println(list.get(0));
            }
        }
    }

When declaring a variable with var (introduced in Java 10), the compiler sometimes infers one of these non-denotable types. This is why some variables declared with var cannot be assigned to or typed explicitly without losing precision or functionality.

Why Does This Matter?

Non-denotable types extend Java's expressiveness, especially for:

  • Anonymous class usage: The type inferred preserves the anonymous class's full structure, including methods beyond superclass/interface declarations.
  • Enhanced local variable inference: var lets the compiler deduce precise types not writable explicitly in source code, often improving code maintainability.

A Practical Example: Incrementing a Counter in a Lambda Without Atomic Types

Mutability inside lambdas is limited in Java. Variables captured by lambdas must be effectively final, so modifying local primitives directly isn't possible. The common approach is to use AtomicInteger or a one-element array for mutation.

However, by leveraging a non-denotable anonymous class type, it is possible to mutate state inside a lambda without using atomic types.

public class Main {
    public static void main(String[] args) {
        // counter is an anonymous class instance with mutable state (non-denotable type)
        var counter = new Object() {
            int count = 0;
            void increment() { count++; }
            int getCount() { return count; }
        };

        // Lambda expression capturing 'counter' and incrementing the count
        java.util.function.Consumer<Integer> incrementer = (i) -> counter.increment();

        // Invoking the lambda multiple times to increment the internal counter
        for (int i = 0; i < 5; i++) {
            incrementer.accept(i);
        }

        System.out.println("Counter value: " + counter.getCount());  // Outputs 5
    }
}

How this works:

  • The counter variable's type is inferred as the unique anonymous class type (non-denotable).
  • This anonymous class contains a mutable field (count) and methods to manipulate and access it.
  • The lambda (incrementer) invokes the method increment() on the anonymous class instance, modifying its internal state.
  • This avoids the need for an AtomicInteger or mutable containers like arrays.
  • Access to the additional method increment() (which is not part of regular interfaces) showcases the benefit of the precise anonymous class type inference.

Benefits of This Approach

  • Avoids clutter and complexity from atomic classes or array wrappers.
  • Keeps code safe within single-threaded or controlled contexts (not thread-safe, so take care in multithreaded scenarios).
  • Utilizes modern Java's type inference power to enable cleaner mutable state management.
  • Demonstrates practical use of non-denotable types, a somewhat abstract but powerful concept in Java's type system.

Final Thoughts

Non-denotable types may seem like compiler internals, but they shape everyday programming modern Java developers do, especially with var and lambdas. Ignoring them means missing out on some elegant solutions like mutable lambdas without extra overhead.

Understanding and utilizing non-denotable types open up possibilities to leverage Java's type system sophistication while writing concise, expressive, and idiomatic code.