|
1 | 1 | package concurrency.future; |
2 | 2 |
|
| 3 | +import java.util.concurrent.Callable; |
| 4 | +import java.util.concurrent.ExecutionException; |
| 5 | +import java.util.concurrent.ExecutorService; |
| 6 | +import java.util.concurrent.Executors; |
| 7 | +import java.util.concurrent.FutureTask; |
| 8 | +import lombok.extern.slf4j.Slf4j; |
| 9 | + |
| 10 | +@Slf4j |
3 | 11 | public class CallbackEx { |
4 | 12 |
|
5 | | - interface Callback { |
6 | | - void onSuccess(); |
| 13 | + interface SuccessCallBack<T> { |
| 14 | + void onSuccess(T t); |
| 15 | + } |
| 16 | + |
| 17 | + interface ExceptionCallBack { |
| 18 | + void onError(Throwable t); |
| 19 | + } |
| 20 | + |
| 21 | + static class CallbackFutureTask<T> extends FutureTask<T> { |
| 22 | + |
| 23 | + private final SuccessCallBack<T> sc; |
| 24 | + private final ExceptionCallBack ec; |
| 25 | + public CallbackFutureTask(Callable<T> callable, SuccessCallBack<T> onSuccess, ExceptionCallBack onError) { |
| 26 | + super(callable); |
| 27 | + this.sc = onSuccess; |
| 28 | + this.ec = onError; |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + protected void done() { |
| 33 | + try { |
| 34 | + sc.onSuccess(get()); |
| 35 | + } catch (InterruptedException e) { |
| 36 | + throw new RuntimeException(e); |
| 37 | + } catch (ExecutionException e) { |
| 38 | + ec.onError(e); |
| 39 | + } |
| 40 | + } |
7 | 41 | } |
8 | 42 |
|
9 | | - public static void main(String[] args) { |
| 43 | + public static void main(String[] args) throws InterruptedException { |
| 44 | + log.debug("Enter"); |
| 45 | + final ExecutorService executorService = Executors.newCachedThreadPool(); |
| 46 | + |
| 47 | + final long startTime = System.currentTimeMillis(); |
| 48 | + |
| 49 | + // non-blocking and asynchronous and |
| 50 | + CallbackFutureTask<String> future = new CallbackFutureTask<>( |
| 51 | + () -> { |
| 52 | + log.debug("Processing task asynchronously"); |
| 53 | + try { |
| 54 | + Thread.sleep(2000); |
| 55 | + } catch (InterruptedException e) { |
| 56 | + throw new RuntimeException(e); |
| 57 | + } |
| 58 | + |
| 59 | + return "AsyncResult"; |
| 60 | + }, |
| 61 | + s -> log.info("Result: " + s), |
| 62 | + e -> log.error("Error: " + e.getMessage()) |
| 63 | + ); |
10 | 64 |
|
| 65 | + executorService.execute(future); |
| 66 | + executorService.shutdown(); |
11 | 67 |
|
| 68 | + log.debug("Is the async task done? " + future.isDone()); |
| 69 | + log.debug("Processing the other task"); |
| 70 | + Thread.sleep(1000); |
| 71 | + log.debug("Exit " + (System.currentTimeMillis() - startTime)); |
12 | 72 | } |
13 | 73 |
|
14 | 74 | } |
0 commit comments