How to handle request / response

Michael.Newcomb at gdc4s.com Michael.Newcomb at gdc4s.com
Mon Jul 11 09:06:53 EDT 2011


Here is the basis for my Request object:

public abstract class AbstractRequest<R>
  implements Request<R>
{
  protected long id;

  protected R response;
  protected Throwable cause;

  protected final CountDownLatch responseLatch = new CountDownLatch(1);

  public long getId()
  {
    return id;
  }

  public void setId(long id)
  {
    this.id = id;
  }

  public R getResponse()
    throws InterruptedException, Exception
  {
    responseLatch.await();

    if (cause != null)
    {
      throw new Exception(cause);
    }
    return response;
  }

  @SuppressWarnings("unchecked")
  public void setResponse(Object response)
  {
    this.response = (R) response;

    responseLatch.countDown();
  }

  public void operationComplete(ChannelFuture future)
    throws Exception
  {
    if (!future.isSuccess())
    {
      cause = future.getCause();

      responseLatch.countDown();
    }
  }
}

I use a CoundDownLatch but you could just as easily use the standard
synchronized/wait semantics.

The Request is a ChannelFutureListener so that if there is a failure to
send the data, getResponse() will throw that error.

-----Original Message-----
From: netty-users-bounces at lists.jboss.org
[mailto:netty-users-bounces at lists.jboss.org] On Behalf Of Jonathan
Arnold
Sent: Friday, July 08, 2011 4:34 PM
To: netty-users at lists.jboss.org
Subject: Re: How to handle request / response

On Fri, 8 Jul 2011 12:41:59 -0700
<Michael.Newcomb at gdc4s.com> wrote:

> This is an example of what I do for request/response. I edited it in
> e-mail, so excuse any typos. 

Thanks for the ideas!

> Send request:
> Request<String> r = new MyRequest();
> channel.write(r);
> String s = r.getResponse();

The getResponse is the tricky part for me. How do you make it wait for
a response? Is that a function of the fact that the Requests interface
extends the ChannelFutureListener?

> public interface Request<R>
>   extends ChannelFutureListener
> {
>   long getId();
> 
>   void setId(long id);
> 
>   R getResponse()
>     throws InterruptedException, Exception;
> 
>   void setResponse(Object response);
> }

-- 
Jonathan Arnold        Webstream: http://hieronymus.soup.io

Talent wins games, but team work and intelligence wins championships.
Michael Jordan

_______________________________________________
netty-users mailing list
netty-users at lists.jboss.org
https://lists.jboss.org/mailman/listinfo/netty-users



More information about the netty-users mailing list