Java: Spring のクラスから明示的に Virtual Thread を使うテンプレ?
こんなんで合ってる?
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Service;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@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();
}
}