Design pattern to handle an asynchronous response in Java

前端 未结 5 2081
遥遥无期
遥遥无期 2021-01-30 18:51

I read answers from similar Q&A

How do you create an asynchronous HTTP request in JAVA? | Asynchronous programming design pattern |
AsyncTask Android - Design P

5条回答
  •  日久生厌
    2021-01-30 18:57

    Asynchronous code can always be made synchronous. The simplest/crudest way is to make the async call, then enter a while loop that just sleeps the current thread until the value comes back.

    Edit: Code that turns an asynchronous callback into synchronous code--again, a crude implementation:

    import java.util.concurrent.*;
    
    public class MakeAsynchronousCodeSynchronous {
        public static void main(String[] args) throws Exception {
            final Listener listener = new Listener();
            Runnable delayedTask = new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        throw new IllegalStateException("Shouldn't be interrupted", e);
                    }
                    listener.onResult(123);
    
                }
            };
            System.out.println(System.currentTimeMillis() + ": Starting task");
            Executors.newSingleThreadExecutor().submit(delayedTask);
            System.out.println(System.currentTimeMillis() + ": Waiting for task to finish");
            while (!listener.isDone()) {
                Thread.sleep(100);
            }
            System.out.println(System.currentTimeMillis() + ": Task finished; result=" + listener.getResult());
        }
    
        private static class Listener {
            private Integer result;
            private boolean done;
    
            public void onResult(Integer result) {
                this.result = result;
                this.done = true;
            }
    
            public boolean isDone() {
                return done;
            }
    
            public Integer getResult() {
                return result;
            }
        }
    }
    

    You could also use a CountDownLatch as recommended by hakon's answer. It will do basically the same thing. I would also suggest you get familiar with the java.util.concurrent package for a better way to manage threads. Finally, just because you can do this doesn't make it a good idea. If you're working with a framework that's based on asynchronous callbacks, you're probably much better off learning how to use the framework effectively than trying to subvert it.

提交回复
热议问题