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

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

My "send" method on the proxy server side should be blocked until a response is received in the request (packets have identifiers for identification and reference purposes) or until a timeout is reached.

If I built it in early versions of Java, I would most likely implement in my proxy a collection of "pending message identifiers" where I would send a message and wait () on the corresponding id (with a timeout), When the response was received, the thread will notify () of the corresponding id.

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

If I went with the solution described above, what is the right way to deal with the potential state of the race in which the answer comes before calling wait ()?

+3
source share
1 answer

An easy way would be to have a Callable that talks to the server and returns a Response.

 // does not block
 Future<Response> response = executorService.submit(makeCallable(request));

 // wait for the result (blocks)
 Response r = response.get();

, .

concurrency . .

concurrency java.nio( , , , , ).

+8

Source: https://habr.com/ru/post/1739558/


All Articles