added the code (#15272)

Co-authored-by: Amit Kumatr <amit.kumar@fyndna.com>
This commit is contained in:
Amit Kumar 2023-12-14 07:19:58 +05:30 committed by GitHub
parent fcc90e0382
commit 97b1af3175
2 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,30 @@
package com.baeldung.callback.completablefuture;
import java.util.concurrent.CompletableFuture;
public class CompletableFutureCallbackExample {
public static void main(String[] args) {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Runnable runnable = downloadFile(completableFuture);
completableFuture.whenComplete((res, error) -> {
if (error != null) {
// handle the exception scenario
} else if (res != null) {
// send data to DB
}
});
new Thread(runnable).start();
}
private static Runnable downloadFile(CompletableFuture<String> completableFuture) {
return () -> {
try {
//logic to download file
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
completableFuture.complete("pic.jpg");
};
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.callback.listenablefuture;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
public class ListenableFutureCallbackExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
ListeningExecutorService pool = MoreExecutors.listeningDecorator(executorService);
ListenableFuture<String> listenableFuture = pool.submit(downloadFile());
Futures.addCallback(listenableFuture, new FutureCallback<String>() {
@Override
public void onSuccess(String result) {
// code to push fileName to DB
}
@Override
public void onFailure(Throwable throwable) {
// code to take appropriate action when there is an error
}
}, executorService);
}
private static Callable<String> downloadFile() {
return () -> {
// Mimicking the downloading of a file by adding a sleep call
Thread.sleep(5000);
return "pic.jpg";
};
}
}