views:

545

answers:

4

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?

+1  A: 

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.

Christoffer
+2  A: 

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.

Cogsy
Why would you spin on a flag if you are using a wait()? Using wait() means you don't need to do that, or yield() or sleep().
Robin
I was thinking of implementing your own .wait(), but yea Object.wait() is another possibility, or possibly Callback.wait(), then the callback can call this.notifyAll()
Cogsy
A: 

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
        }
     }
}
toolkit
It's straight TCP not JMS
Omar Kooheji
+1  A: 

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.

Robin