Java 23

Mehr Handlung, mehr Übersicht

Java Software Engineer

Line of Business Public

Oracle ACE Associate

Merlin Bögershausen / @mboegie

♻️ Recap on Threads ♻️

Threads in general

thread forking
thread states

Threads in Java

class ExampleThread extends Thread {
  public void run() { /* Do it */}
}
var t1 = new ExampleThread();

class ExampleRunable implements Runable {
  public void run() { /* Do it again */}
}
var runable = new ExampleRunable();
var t2 = new Thread(runable);

t2.start(); t1.start();
t2.join(); t1.join();

Concurrency Models [1]

ExecutorService

  • Thread Pool Management

  • reuse OS Threads

CompletableFuture

  • Composing asyncron operations

  • handling Results

1. Credits to Hanno Embregts on Devoxx.BE 2024, slides

JEP 444 Virtual Threads

Virtual threads are lightweight threads that improve Maintanace and Obervability.

Platform vs. Virtual

thread normal

Creation of Virtual

Thread.ofVirtual().start(() -> doIOStuffInParallel());

Thread.ofPlatform() // is new as well

Better use Executors

Executors.newVirtualThreadPerTaskExecutor()
	.submit(() -> doIOStuffInParallel());

Awesome, now what?

  • Lightweight?

  • Maintainabllility?

  • Oberservability?

Example we Work with

example class

JEP 481 Scoped Values

Share immutable data between callees within a thread and child threads.

Concept

scoped values concept

Goals of Scoped Values

  • 🥅 Ease of use

  • 🥅 Comprehensibility

  • 🥅 Robustness

  • 🥅 Performance

ScopesValues API

final static ScopedValue<SSLContext> VAL
                    = ScopedValue.newInstance();

ScopedValue.where(VAL, value)
           .run(() -> VAL.get());

ScopedValue.runWhere(VAL, value, () -> /* ... */);

Framework - Creation

private final static ScopedValue<Map<String, String>>
    INPUTDATA = ScopedValue.newInstance();

private final static ScopedValue<SSLContext>
    SSL_CTX = ScopedValue.newInstance();

Framework -Config

ScopedValue.Carrier executionScope = ScopedValue
    .where(INPUTDATA, Map.copyOf(data))
    .where(SSL_CTX, SSLContext.getDefault());

Framework - Execution

// ScopedValue.Carrier executionScope;

for (var r : rules) {
    executionScope.run(r::fire);
}

Usercode - Access I

//ScopedValue<Map<String, String>> INPUTDATA;

String inputName = INPUTDATA
        .orElseThrow(new IllegalArgumentException())
        .getOrDefault("name", "JON");

Usercode - Access II

// ScopedValue<SSLContext> SSL_CTX

if(SSL_CTX.isBound()) {
    intputName = "%s %s".formatted(
            inputName, getLastName(SSL_CTX.get()));
}

Comparison [1]

ScopedValues

  • Immutable Carrier

  • Same instance

  • Rebindable

ThreadLocal

  • Supplier

  • Instance per Thread

  • Mutable Value

1. full length comparison by Alex Klimenko on Medium

JEP 480 Stuctured Concurrency

Treat groups of related tasks running in different threads as a single unit of work, thereby streamlining error handling and cancellation, improving reliability, and enhancing observability.

Concept

structured concurrency concept

Task Scope API

public class StructuredTaskScope<T> implements AutoCloseable {
  public <U extends T> Subtask<U>
        fork(Callable<? extends U> task);

  public StructuredTaskScope<T> join()
        throws InterruptedException;
  public StructuredTaskScope<T> joinUntil(Instant deadline)
        throws InterruptedException, TimeoutException;

  public void shutdown();
  public void close();
}

Shutdown Policies

ShutdownOnFailure first task failed

ShutdownOnSuccess first task successfully terminates

Structured Concurrency in Rule

try (var scope = new StructuredTaskScope.ShutdownOnFailure()){
    Supplier<String> adr = scope.fork(() -> readAddress());

    scope.join().throwIfFailed();

    var addres = adr.get();
} catch (ExecutionException | InterruptedException e) {
    throw new RuntimeException(e);
}

Final words

  • Never pool VirtualThreads

  • Migrate immediately

  • ThreadLocal never mutated ⇒ ScopedValues

  • IO Concurrency ⇒ StructuredConcurrency

GitHub GIST with full code

Contact

Me

MBoegie@fosstodon.org // @MBoegi // MBoegers

adesso

Infos // DevBlog

Approach direct

I'm here all day with cookies!

Jobs

qrcode adesso jobs

Image Credits

  • Knited Speach Blubled generetd with deepai.org

  • Virtual reality background generetd with deepai.org

  • Elderly Person handing over treats generated with deepai.org

  • Chaos of pipes and notations generated with deepai.org