Java: Spring のクラスから明示的に Virtual Thread を使うテンプレ?
こんなんで合ってる?
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Service;
import java.util.concurrent.*;
@Service
public class FooService {
private final ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
@PreDestroy
public void destroy() {
executorService.shutdown();
try {
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
public String find() throws ExecutionException, InterruptedException {
var future = this.executorService.submit(() -> {
// some IO process
return "result";
});
// some code
return future.get();
}
// こっちの方が正解?
public String find2() throws ExecutionException, InterruptedException {
var future = CompletableFuture.supplyAsync(
() -> {
// some IO process
return "result";
}, this.executorService);
// some code
return future.get();
}
}