




Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!





javac --release 27 --enable-preview PrimitivePatterns.java java --enable-preview PrimitivePatterns
java --enable-preview PrimitivePatterns.java
27 --enable-preview
--enable-preview
// 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); }
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
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
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; }
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: "
// 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