Avancerade trådmönster

Optimera kod i Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Grunderna i trådpooler

Att skapa trådar är dyrt!

$$

Trådpooler:

  • Återanvänder befintliga trådar
  • Begränsar antalet parallella trådar
  • Hanteras via gränssnittet ExecutorService
Optimera kod i Java

Skapa trådpooler

// Fixed thread pool with 4 threads
ExecutorService fixedPool = Executors.newFixedThreadPool(4);


// Cached thread pool that grows as needed ExecutorService cachedPool = Executors.newCachedThreadPool();
// Single-threaded executor ExecutorService singleExecutor = Executors.newSingleThreadExecutor();
Optimera kod i Java

Skicka in uppgifter

ExecutorService executor = Executors.newFixedThreadPool(4);

// Submit a task with no return value
executor.execute(() -> System.out.println("Simple task"));

// Submit a task with a return value (Callable)
Future<Integer> future = executor.submit(() -> {
    Thread.sleep(1000);
    return 42;
});

// Get result from Future (blocks until complete)
int result = future.get();
Optimera kod i Java

Stänga ner executors

// Signal shutdown, but continue running existing tasks
executor.shutdown();


// Wait for termination (with timeout) boolean terminated = executor.awaitTermination(5, TimeUnit.SECONDS);
// Force immediate shutdown, canceling running tasks executor.shutdownNow();
Optimera kod i Java

CompletableFuture

  • CompletableFuture
  • Del av Javas concurrency-API sedan Java 8
  • Modernt sätt att hantera asynkron programmering
  • Kan slutföras manuellt eller via en Function
  • Möjliggör kedjeoperationer med callbacks
  • Fungerar med eller utan explicita trådpooler
Optimera kod i Java

Skapa completable futures

// Run async with default executor
CompletableFuture<Void> runAsync = 
    CompletableFuture.runAsync(() -> performTask());

// Supply async with custom executor ExecutorService executor = Executors.newCachedThreadPool(); CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(() -> fetchData(), executor);
Optimera kod i Java

Kedja operationer

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> fetchUserData(userId))
    .thenApply(data -> extractUsername(data))
    .exceptionally(ex -> "Unknown user");

// Access to result when ready
future.thenAccept(result -> System.out.println(result));
Optimera kod i Java

Nu kör vi en övning!

Optimera kod i Java

Preparing Video For Download...