Help needed to create asynchronous java method

bachra04
bachra04 used Ask the Experts™
on
Hi guys,

I need to create an asynchronous method in java. I thought about using two threads and a queue similar to C++ so I can push the method to the queue in one thread. And another thread reads the method executes it and then call the handler method. Is that possible in java ? any sample code will be appreciated ?

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
by the way I already saw the following link so no need to post it again :
http://cephas.net/blog/2004/02/02/asynchronous-method-invocation-in-java/

Thanks
Do you need to handle multiple potential calls to this method concurrently (or in some order)?  Just wondering why you're looking to create a queue with callbacks.  If that's the case, your best bet might be to implement the async method as a Runnable object and define an interface for the callback method.  Then, provide an implementation of that interface to the Runnable and submit it to an ExecutorService (java.util.concurrent) to manage the threads for you.  This approach will run your callback method on the same thread that ran the method, but I don't know if that is a requirement for you or not.


public interface AsyncCallback {
    void asyncComplete(Object result);
    // optional
    void asyncError(Exception e);
}

public class AsyncMethod implements Runnable {
    private AsyncCallback callback;

    public AsyncMethod(AsyncCallback callback) {
        this.callback = callback;
    }

    public void run() {
        try {
            // do something
            callback.asyncComplete(...);
        } catch (Exception e) {
            callback.asyncError(e);
        }
    }
}

public class AsyncDriver {
    private ExecutorService executorService;

    public AsyncDriver() {
        executorService = Executors.XXX(); // use appropriate executor
    }

    public void callAsync(AsyncMethod method) {
        executorService.submit(method);
    }
}

Open in new window

Author

Commented:
Hi Gordon,

I don't have a requirement to execute the callback method in the same thread as the main method. but I do have a requirement of very high level of calls to the the asynchMethod ( Thousands per second), that's why I thought about having a queue.
But I would assume that the executorService is using an internal queue to do that ?
Yes.  Take a look at the java.util.concurrent.Executors class, it provides several factory methods for creating different types of Executors to manage the size of the thread pool.  I think that framework will fit your needs.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial