Java'da Kod Optimizasyonu
Pavlos Kosmetatos
Lead Engineer @Wealthyhood
İş parçacığı oluşturmak maliyetlidir!
$$
İş parçacığı havuzları:
ExecutorService arayüzüyle yönetilir// 4 iş parçacıklı sabit havuz ExecutorService fixedPool = Executors.newFixedThreadPool(4);// İhtiyaca göre büyüyen önbellekli havuz ExecutorService cachedPool = Executors.newCachedThreadPool();// Tek iş parçacıklı yürütücü ExecutorService singleExecutor = Executors.newSingleThreadExecutor();
ExecutorService executor = Executors.newFixedThreadPool(4);
// Geri dönüş değeri olmayan görev gönder
executor.execute(() -> System.out.println("Simple task"));
// Geri dönüş değerli görev (Callable) gönder
Future<Integer> future = executor.submit(() -> {
Thread.sleep(1000);
return 42;
});
// Future sonucunu al (tamamlanana kadar bloklar)
int result = future.get();
// Kapatmayı sinyalle, mevcut görevler sürer executor.shutdown();// Sonlanmayı bekle (zaman aşımıyla) boolean terminated = executor.awaitTermination(5, TimeUnit.SECONDS);// Anında kapat, çalışan görevleri iptal et executor.shutdownNow();
CompletableFutureFunction ile tamamlanabilir// Varsayılan yürütücü ile async çalıştır CompletableFuture<Void> runAsync = CompletableFuture.runAsync(() -> performTask());// Özel yürütücü ile async değer üret ExecutorService executor = Executors.newCachedThreadPool(); CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(() -> fetchData(), executor);
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> fetchUserData(userId))
.thenApply(data -> extractUsername(data))
.exceptionally(ex -> "Unknown user");
// Hazır olduğunda sonuca erişim
future.thenAccept(result -> System.out.println(result));
Java'da Kod Optimizasyonu