I am writing a multi-threaded server, with needs to handle client requests and return them back to the client when done.
I have a list of concurrent client connections object, which pass on payloads to a common queue. After going through the queue, the payloads are handled by the server and responses are generated.
The problem I have is that I have no idea how to notify the client that the server has finished processing.
This is the thread that handles client payloads, payLoad is a BlockingQueue, which was previously loaded by client threads:
Thread messageHandling = new Thread() {
public void run(){
while(true){
try{
Object payLoad= payLoads.take();
// Do some handling
// SEND REPLY BACCK TO THE CLIENT
}
catch(InterruptedException e){ }
}
}
};
At the same time, on the client side, the following is happening:
{
...
payloads.add(payLoad)
/// Sleep until the server is done doing its logic with the payload
}
The commented bits are where I am having trouble. I have no idea how to implements a mechanism where the client thread will wait until the request is processed and, once it is, I do not know how to send the reply back to the client.
I have spent plenty of time researching, looked at the consumer/producer problem, wait/notify mechanism, etc, but nothing seems to be similar to this particular problem.
Any help would be greatly appreciated.
You need to store client connection information next to payload in your payloads
.
Create class with two fields. One of them will be your payload and another is something that allow you to identify your client.
In your // SEND REPLY BACCK TO THE CLIENT
just send response. No need to wait in /// Sleep until the server is done doing its logic with the payload
Without knowing which way you communicate with client I can't give you better answer.
In case you use sockets "something that allow you to identify your client" will be socket instance.
Other approach will be using SynchronousQueue
.
In // SEND REPLY BACCK TO THE CLIENT
you put your response in it.
In /// Sleep until the server is done doing its logic with the payload
you take response (method will block until response is putted in buffer).
Pass buffer with payload same way as in previous approach.