Docsity

Java 27 latest features, Apuntes de Tecnologías de la Información y la Comunicación

Toggle sidebar
bg1
Java 27 New Features | Part 1: Language & Concurrency
Page 1
Java 27: Language & Concurrency
Part 1 of 3. Primitive patterns, lazy constants and structured concurrency, with runnable examples.
JDK 27 became generally available on 15 September 2026. It is not a long-term support release (JDK 25 is the
latest LTS). It delivers nine JEPs, covered across these three documents.
JEP Feature Status Part
523 G1 is the default garbage collector in all environments Final 3
527 Post-quantum hybrid key exchange for TLS 1.3 Final 2
531 Lazy Constants 3rd preview 1
532 Primitive types in patterns, instanceof and switch 5th preview 1
533 Structured Concurrency 7th preview 1
534 Compact object headers by default Final 3
536 JFR in-process data redaction Final 2
537 Vector API 12th incubator 3
538 PEM encodings of cryptographic objects 3rd preview 2
Running the examples
All three features in this part are preview features: complete and usable, but allowed to change or be removed.
Enable them at compile time and at run time.
# compile and run
javac --release 27 --enable-preview PrimitivePatterns.java
java --enable-preview PrimitivePatterns
# or run the source file directly
java --enable-preview PrimitivePatterns.java
Maven (use for experiments, not for a library you publish):
<!-- maven-compiler-plugin -->
<configuration>
<release>27</release>
<compilerArgs><arg>--enable-preview</arg></compilerArgs>
</configuration>
<!-- maven-surefire-plugin -->
<configuration><argLine>--enable-preview</argLine></configuration>
1. Primitive types in patterns, instanceof and switch (JEP 532)
Pattern matching previously worked with reference types, and switch accepted only a limited set of primitives with
constant labels. With this preview, every primitive type can be used in instanceof, in switch, and nested inside
record patterns.
Before and after
// Before: manual range check, then a cast
if (dbId >= Integer.MIN_VALUE && dbId <= Integer.MAX_VALUE) {
int i = (int) dbId;
use(i);
}
// Java 27 preview: matches only when the conversion loses nothing
if (dbId instanceof int i) {
use(i);
}
pf3
pf4
pf5
pf8

Vista previa parcial del texto

¡Descarga Java 27 latest features y más Apuntes en PDF de Tecnologías de la Información y la Comunicación solo en Docsity!

Java 27: Language & Concurrency

Part 1 of 3. Primitive patterns, lazy constants and structured concurrency, with runnable examples.

JDK 27 became generally available on 15 September 2026. It is not a long-term support release (JDK 25 is the

latest LTS). It delivers nine JEPs, covered across these three documents.

JEP Feature Status Part

523 G1 is the default garbage collector in all environments Final 3

527 Post-quantum hybrid key exchange for TLS 1.3 Final 2

531 Lazy Constants 3rd preview 1

532 Primitive types in patterns, instanceof and switch 5th preview 1

533 Structured Concurrency 7th preview 1

534 Compact object headers by default Final 3

536 JFR in-process data redaction Final 2

537 Vector API 12th incubator 3

538 PEM encodings of cryptographic objects 3rd preview 2

Running the examples

All three features in this part are preview features: complete and usable, but allowed to change or be removed.

Enable them at compile time and at run time.

compile and run

javac --release 27 --enable-preview PrimitivePatterns.java java --enable-preview PrimitivePatterns

or run the source file directly

java --enable-preview PrimitivePatterns.java

Maven (use for experiments, not for a library you publish):

27 --enable-preview

--enable-preview

1. Primitive types in patterns, instanceof and switch (JEP 532)

Pattern matching previously worked with reference types, and switch accepted only a limited set of primitives with

constant labels. With this preview, every primitive type can be used in instanceof, in switch, and nested inside

record patterns.

Before and after

// Before: manual range check, then a cast if (dbId >= Integer.MIN_VALUE && dbId <= Integer.MAX_VALUE) { int i = (int) dbId; use(i); }

// Java 27 preview: matches only when the conversion loses nothing if (dbId instanceof int i) { use(i); }

What is new Example

Exactness check instead of a silent lossy cast 1000 instanceof byte b is false

Bind the switched value case int s when s >= 500

switch on long, float, double and boolean case 10_000_000_000L

Primitive patterns inside records case Reading(int i)

PrimitivePatterns.java

public class PrimitivePatterns {

static String httpStatus(int status) { return switch (status) { case 200 -> "OK"; case 404 -> "Not Found"; case int s when s >= 500 -> "Server error " + s; case int s -> "Other " + s; // binds the value }; }

static String narrow(long dbId) { // e.g. an Oracle NUMBER column if (dbId instanceof int i) { // true only if no data is lost return dbId + " fits in int: " + i; } return dbId + " needs long"; }

static String size(long bytes) { return switch (bytes) { // switch on long case 0L -> "empty"; case long b when b < 1_048_576L -> "small"; case 10_000_000_000L -> "exactly 10 billion"; case long b -> "large"; }; }

static String flag(boolean enabled) { return switch (enabled) { // exhaustive, no default case true -> "ON"; case false -> "OFF"; }; }

record Reading(double value) {}

static String classify(Reading r) { return switch (r) { // primitive inside a record pattern case Reading(int i) -> "whole number " + i; case Reading(double d) -> "decimal " + d; }; }

public static void main(String[] args) { System.out.println(httpStatus(200)); System.out.println(httpStatus(503)); System.out.println(httpStatus(301)); System.out.println(narrow(42L)); System.out.println(narrow(3_000_000_000L)); System.out.println(size(512)); System.out.println(size(10_000_000_000L)); System.out.println(flag(true)); System.out.println(classify(new Reading(21.0))); System.out.println(classify(new Reading(21.5)));

int big = 16_777_217; System.out.println("int -> float exact? " + (big instanceof float f)); System.out.println("1000 -> byte exact? " + (1000 instanceof byte b)); } }

LazyConstants.java

import module java.base;

public class LazyConstants {

static class ReportEngine { ReportEngine() { System.out.println(" building ReportEngine (once)"); } String render(String name) { return "report:" + name; } }

// Computed on first get(), at most once, even with many threads private static final LazyConstant ENGINE = LazyConstant.of(ReportEngine::new);

// Lazy list: each element is created on first access static final List PARTITIONS = List.ofLazy(3, i -> { System.out.println(" init partition " + i); return "partition-" + i; });

// Lazy map: fixed key set, values computed per key static final Map TOPICS = Map.ofLazy(Set.of("orders", "payments"), key -> { System.out.println(" resolving topic " + key); return "prod." + key + ".v1"; });

enum Feature { AUDIT, METRICS, TRACING }

// Lazy set (new in JDK 27): membership decided per element, once static final Set ENABLED = Set.ofLazy(EnumSet.allOf(Feature.class), f -> { System.out.println(" checking " + f); return f != Feature.TRACING; });

public static void main(String[] args) throws Exception { System.out.println("started, nothing initialized yet");

try (var pool = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 3; i++) { pool.submit(() -> ENGINE.get().render("daily")); } } System.out.println(ENGINE.get().render("monthly"));

System.out.println(PARTITIONS.get(1)); System.out.println(PARTITIONS.get(1)); // cached System.out.println(TOPICS.get("orders")); System.out.println(ENABLED.contains(Feature.AUDIT)); System.out.println(ENABLED.contains(Feature.AUDIT)); // cached System.out.println(ENABLED.contains(Feature.TRACING)); } }

Output (JDK 27) started, nothing initialized yet building ReportEngine (once) report:monthly init partition 1 partition- partition- resolving topic orders prod.orders.v checking AUDIT true true checking TRACING false

Pitfalls and changes in JDK 27

  • isInitialized() and orElse() were removed. Code written for JDK 26 that calls them no longer compiles.
  • The computing function must not return null.
  • A failure is permanent. In our test on JDK 27, when the function threw (or returned null), get() threw

NoSuchElementException, and a second call threw it again without re-running the function. Do not use it for work

that needs retries, such as opening a network connection that may be temporarily down.

  • Keep the holder in a final field so the JVM can optimise it. 3. Structured Concurrency (JEP 533)

StructuredTaskScope treats a group of subtasks running in different threads (virtual threads by default) as one unit

of work. If the task fails, siblings are cancelled; no subtask can outlive the block.

try (var scope = StructuredTaskScope.open(/* joiner, config */)) { var a = scope.fork(() -> callA()); // 1. fork var b = scope.fork(() -> callB()); scope.join(); // 2. join: applies the policy use(a.get(), b.get()); // 3. read results } // 4. close: no thread leaks

What changed in the 7th preview

JDK 26 JDK 27

join() threw FailedException join() throws ExecutionException by default

Joiner Joiner, where R_X is the exception type of join()

onTimeout() timeout(), which returns a result or throws R_X

Configuring the default policy needed an explicit joiner New open(configOperator) overload

Joiner factory join() returns Behaviour

open() (no joiner) null All must succeed; first failure cancels the rest

allSuccessfulOrThrow() List of results All must succeed

anySuccessfulOrThrow() One result First success wins

awaitAllSuccessfulOrThrow() null All must succeed; read each Subtask

allUntil(predicate) List of Subtasks Stops when the predicate matches

StructuredBasics.java

import module java.base; import java.util.concurrent.StructuredTaskScope.Joiner;

public class StructuredBasics {

record Order(String user, int total) {}

static String findUser() throws InterruptedException { Thread.sleep(100); return "imran"; } static int fetchTotal() throws InterruptedException { Thread.sleep(150); return 250; } static String replica(String name, int ms) throws InterruptedException { Thread.sleep(ms); return name; }

Guidelines

  • Subtasks must respond to interruption, otherwise close() waits for them.
  • Only the owner thread may call fork and join. Create a new joiner for every scope.
  • Transactions and security context held in thread-locals do not follow forked threads automatically. Keep

database transaction boundaries inside one subtask or outside the scope.

  • Looking ahead: JEP 543 finalises this API in JDK 28, and InfoQ reports no API changes from this JDK 27

version.

Typed exceptions, timeouts and a custom joiner

StructuredAdvanced.java

import module java.base; import java.util.concurrent.StructuredTaskScope.Joiner; import java.util.concurrent.StructuredTaskScope.Subtask;

public class StructuredAdvanced {

static class ServiceException extends Exception { ServiceException(Throwable cause) { super(cause); } }

// 1. Choose the exception type that join() throws static void typedException() throws InterruptedException { try (var scope = StructuredTaskScope.open( Joiner.allSuccessfulOrThrow( ServiceException::new))) { scope.fork(() -> { throw new IllegalStateException("broker offline"); }); scope.join(); // throws ServiceException } catch (ServiceException e) { System.out.println("typed: " + e.getCause().getMessage()); } }

// 2. Timeout and scope name static void timeout() throws InterruptedException { try (var scope = StructuredTaskScope.open( Joiner.allSuccessfulOrThrow(), cf -> cf.withName("price-lookup") .withTimeout(Duration.ofMillis(100)))) { scope.fork(() -> { Thread.sleep(2_000); return "slow"; }); scope.join(); } catch (ExecutionException e) { System.out.println("timeout cause: "

  • e.getCause().getClass().getSimpleName()); } }

// 3. Custom joiner: keep partial results, never fail static class Successful implements Joiner, RuntimeException> { private final Queue results = new ConcurrentLinkedQueue<>();

@Override public boolean onComplete(Subtask task) { // runs concurrently if (task.state() == Subtask.State.SUCCESS) { results.add(task.get()); } return false; // do not cancel } @Override public List result() { return List.copyOf(results); } @Override public List timeout() { return result(); } // partial results }

static List partial() throws InterruptedException { try (var scope = StructuredTaskScope.open( new Successful(), cf -> cf.withTimeout(Duration.ofMillis(300)))) { scope.fork(() -> "cache"); scope.fork(() -> { throw new IOException("db"); }); scope.fork(() -> { Thread.sleep(5_000); return "remote"; }); return scope.join(); } }

public static void main(String[] args) throws Exception { typedException(); timeout(); System.out.println("partial: " + partial()); } }

Output (JDK 27) typed: broker offline timeout cause: CancelledByTimeoutException partial: [cache]

Sources: Oracle: Structured Concurrency in Java SE 27 | InfoQ: JEP 533 for JDK 27 | InfoQ: JEP 543 finalises Structured

Concurrency in JDK 28 | OpenJDK CSR: Lazy Constants (Third Preview) | JEP 530: Primitive types in patterns (previous preview) | HowToDoInJava: all 9 JEPs in JDK 27