Callable with Future
Future can be used along with callable to get return from the threads execution.
public String getDataWithGET(String url, int i) {
System.out.println("Stated" + i);
WebClient web = WebClient.create(url);
String x = web.get().exchangeToMono(
t -> t.statusCode().equals(HttpStatusCode.valueOf(200)) ? t.bodyToMono(String.class) : t.createError())
.block();
System.out.println(x);
return x;
}
void getData() {
try {
ExecutorService exe = Executors.newFixedThreadPool(10);
ArrayList<Future<String>> listFuture = new ArrayList<Future<String>>();
for (int i = 0; i < 20; i++) {
int num = i;
String url = "https://www.deckofcardsapi.com/api/deck/new/shuffle/?deck_count=" + i;
Callable<String> c = () -> getDataWithGET(url, num);
Future<String> future = exe.submit(c);
listFuture.add(future);
}
System.out.println("Fetting done : Response size "+listFuture.size());
for(Future<String> f: listFuture) {
System.out.println(f.get());
}
exe.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
Ref : https://www.digitalocean.com/community/tutorials/java-callable-future-example
Comments
Post a Comment