¿Cómo matar hilos relacionados con CompletableFuture?
Tengo un método que verifica el tiempo de ejecución de CompletableFuture. Si dicho CompletableFuture se ejecuta durante más de 2 segundos, quiero eliminar esta tarea. Pero, ¿cómo puedo hacerlo si no tengo control sobre el hilo donde se ejecutan los métodos CompletableFuture?
final CompletableFuture<List<List<Student>>> responseFuture = new CompletableFuture<>();
responseFuture.supplyAsync(this::createAllRandomGroups)
.thenAccept(this::printGroups)
.exceptionally(throwable -> {
throwable.printStackTrace();
return null;
});
createAllRandomGroups ()
private List<List<Student>> createAllRandomGroups() {
System.out.println("XD");
List<Student> allStudents = ClassGroupUtils.getActiveUsers();
Controller controller = Controller.getInstance();
List<List<Student>> groups = new ArrayList<>();
int groupSize = Integer.valueOf(controller.getGroupSizeComboBox().getSelectionModel().getSelectedItem());
int numberOfGroupsToGenerate = allStudents.size() / groupSize;
int studentWithoutGroup = allStudents.size() % groupSize;
if (studentWithoutGroup != 0) groups.add(this.getListOfStudentsWithoutGroup(allStudents, groupSize));
for(int i = 0; i < numberOfGroupsToGenerate; i++) {
boolean isGroupCreated = false;
while (!isGroupCreated){
Collections.shuffle(allStudents);
List<Student> newGroup = this.createNewRandomGroupOfStudents(allStudents, groupSize);
groups.add(newGroup);
if (!DataManager.isNewGroupDuplicated(newGroup.toString())) {
isGroupCreated = true;
allStudents.removeAll(newGroup);
}
}
}
DataManager.saveGroupsToCache(groups);
return groups;
}
printGroups ()
private void printGroups(List<List<Student>> lists) {
System.out.println(lists);
}
Esta declaraciónresponseFuture.cancel(true);
no mata el hilo donde responseFuture está haciendo los métodos. Entonces, ¿cuál es la forma más elegante de terminar el hilo CompletableFuture?