How to implement blocking request-reply using Java concurrency primitives?

Posted by Uri on Stack Overflow See other posts from Stack Overflow or by Uri
Published on 2010-04-02T02:41:28Z Indexed on 2010/04/02 2:43 UTC
Read the original article Hit count: 291

Filed under:
|
|

My system consists of a "proxy" class that receives "request" packets, marshals them and sends them over the network to a server, which unmarshals them, processes, and returns some "response packet".

My "submit" method on the proxy side should block until a reply is received to the request (packets have ids for identification and referencing purposes) or until a timeout is reached.

If I was building this in early versions of Java, I would likely implement in my proxy a collection of "pending messages ids", where I would submit a message, and wait() on the corresponding id (with a timeout). When a reply was received, the handling thread would notify() on the corresponding id.

Is there a better way to achieve this using an existing library class, perhaps in java.util.concurrency?

If I went with the solution described above, what is the correct way to deal with the potential race condition where a reply arrives before wait() is invoked?

© Stack Overflow or respective owner

Related posts about java

Related posts about concurrency