Implementing synchronous network call in java awaiting ack message?

How could you implement a uniform wait before a full method call in Java?

Basically what I want to do is a hava method that sends a message over the network to the server application and waits until it receives the appropriate Ack message from the server, either the operation succeeded, or the operation failed and an error message.

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

would it be wise to construct a callback class to pass it to my previous method and then do a wait operation, and on callback does that class notify?

0


a source to share


4 answers


Short answer: Yes. I'm a fan of using what is already in the class library, what you describe sounds just like the Observer pattern for which you already have Observer / Observable interfaces if you are using J2SE.



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

+1


a source


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



Retaining the need to rewrite the alternative blocking communication channel.

+2


a source


Yes, use your existing method as you suggest. Create a callback in the sync method call that will coordinate with the sync method call via wait () / notify (). The sync method will invoke async and then wait (). When the callback is called, it calls the notify () function to wake up the sync method so that it can return results.

+1


a source


Please ignore if you are not using JMS.

If you are using JMS, you can use QueueRequestor , which is an implementation of the Request integration template .

That is, the following call appears synchronously with the client, although 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
        }
     }
}

      

0


a source







All Articles