Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of AsyncListener#onError

I don't understand when AsyncListener#onError method is called. Javadoc doesn't help:

Notifies this AsyncListener that an asynchronous operation has failed to complete.

How could it fail? How can I reproduce this error?

UPDATE:

// in HttpServlet doGet method
AsyncContext asyncContext = req.startAsync();
asyncContext.addListener(new AsyncListener() {
    // some code
    @Override
    public void onError(AsyncEvent event) {
        // when is it called?
    }
});
executeInSomeOtherThread(asyncContext);

What do I need to do in other thread to fail this async operation?

like image 601
dream brother Avatar asked Feb 18 '14 16:02

dream brother


1 Answers

onError will be called if there was an Exception thrown while carrying out the asynchronous operation.

They are typically Throwables that extend java.io.IOException caused by I/O failures because of an unreliable connection or protocol level exceptions due to a logical error because of a mismatch between the client and the server.

You can get the Throwable when onError is invoked by calling:

event.getThrowable();

EDIT to address mjaggard's follow-on questions

Forgetting about AsyncContext for a second, consider the following class:

public class MyRunnableClass implements Runnable {
    private Listener mListener;

    interface Listener {
        void onError(Throwable error);
    }

    public void setListener(Listener listener) {
        mListener = listener;
    }

    @Override
    public void run() {
        // Some important code to be executed goes here

        // Pretend an exception was caught in a try/catch/finally
        // block that was doing an I/O operation

        Throwable someError = new IOException();

        if (mListener != null) {
            mListener.onError(someError);
        }
    }
}

Is it more clear now how the listener's onError method will be invoked because an exception was raised when MyRunnableClass's run method was invoked?

MyRunnableClass mrc = new MyRunnableClass();
mrc.setListener(new Listener() {
    @Override
    public void onError(Throwable error) {

    }
});

Executors.newSingleThreadScheduledExecutor().schedule(mrc, 1000L, TimeUnit.MILLISECONDS);

This is no different from how an AsyncContext holds onto a listener and notifies it if it encounters an exception that it wishes to report to the listener. How the run method gets invoked is really secondary to the fact that the owner of the code being executed is also the one that holds a reference to the listener.

like image 117
Michael Krause Avatar answered Oct 07 '22 14:10

Michael Krause