Question

How would you go about implementing the equivellent of a wait until complete method call in Java?

Basically what I want to do is hava a method that sends a message over the network to a server application and waits till it gets the appropriate Ack message from the server with either an operation completed successfully or operation failed and an error message.

I already have a non blocking version of my method which passes a callback class in which has a method that is called on callback.

would it make sense to construct a callback class pass it in to my previous method and then perform a wait operation and on the callback have that class do a notify?

Was it helpful?

Solution

Short answer: Yes. I'm a fan of using what's in the class library already, what you describe sounds a lot like an Observer pattern, for which you have the Observer/Observable interfaces already, assuming you're using J2SE.

EDIT: Something was wrong with my coffee :) Obviously, what I meant to say was check out what's in java.util.concurrent package, specifically the Future<> and ExecutorService classes.

OTHER TIPS

Adding a .wait() to your callback class would be the easiest path. It can sit there spinning on some flag until your callback switches it, just be sure to include Thread.yield() or .sleep() in your loop.

Saves having to rewrite an alternative blocking comms channel.

Yes, use your existing method like you are suggesting. Create the callback in your sync method call that will coordinate with the sync method call via wait()/notify(). The sync method will call the async one and then wait(). When the callback is called, it will call notify() to wake up the sync method so it can return the results.

Please ignore if you're not using JMS.

If you are using JMS, then you could use a QueueRequestor, which is an implementation of the Request Reply integration pattern.

That is, the following call appears synchronous to the client, even though asynchronous messages are used:

QueueRequestor requestor = null;
try {
    requestor = new QueueRequestor(session, queue); 
    Message response = requestor.send(request);
} finally {
    if (requestor == null) {
        try {
            requestor.close();
        } catch (JMSException e) {
            // log error message
        }
     }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top