Created
April 20, 2022 08:51
-
-
Save cyberdak/dae60474ed313005820331f50bc12f91 to your computer and use it in GitHub Desktop.
callback hell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.bj58.loc.service.util; | |
| import com.google.common.util.concurrent.*; | |
| import org.jetbrains.annotations.Nullable; | |
| import java.util.concurrent.*; | |
| public class ListenableFutureLearn { | |
| private static final int processors = Runtime.getRuntime().availableProcessors(); | |
| private static final ThreadFactory threadFactory = | |
| new ThreadFactoryBuilder() | |
| .setDaemon(true) | |
| .setNameFormat("ListenableFutureAdapter-thread-%d") | |
| .build(); | |
| private static final ExecutorService defaultAdapterExecutor = | |
| Executors.newFixedThreadPool(processors,threadFactory); | |
| public static void main(String[] args) { | |
| String string = "test"; | |
| Future<String> future = defaultAdapterExecutor.submit(new Callable<String>() { | |
| @Override | |
| public String call() throws Exception { | |
| return null; | |
| } | |
| }); | |
| ListenableFuture<String> listenInPoolThread = JdkFutureAdapters.listenInPoolThread(future); | |
| Futures.addCallback(listenInPoolThread, new FutureCallback<String>() { | |
| @Override | |
| public void onSuccess(String result) { | |
| System.out.printf("success", result); | |
| Future<String> future1 = defaultAdapterExecutor.submit(new Callable<String>() { | |
| @Override | |
| public String call() throws Exception { | |
| return null; | |
| } | |
| }); | |
| ListenableFuture<String> listenInPoolThread1 = JdkFutureAdapters.listenInPoolThread(future1); | |
| Futures.addCallback(listenInPoolThread1, new FutureCallback<String>() { | |
| @Override | |
| public void onSuccess(@Nullable String s) { | |
| } | |
| @Override | |
| public void onFailure(Throwable throwable) { | |
| } | |
| } | |
| } | |
| @Override | |
| public void onFailure(Throwable t) { | |
| System.err.printf("failure"); | |
| } | |
| }); | |
| } | |
| private static class Task implements Callable<String> { | |
| private final String data; | |
| public Task(String data) { | |
| this.data = data; | |
| } | |
| @Override | |
| public String call() throws Exception { | |
| try { | |
| return "result_Success" + data; | |
| } catch (Exception e) { | |
| return "result_Failure" + data; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment