• Post Reply Bookmark Topic Watch Topic
  • New Topic

Asynchronous socket programming in Java  RSS feed

 
Imran Akbar
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to write a client application which will support multiple threads communicating with a service over a single socket. The responses will be returned randomly on the socket. I'm looking at a design which will use a thread to read all of the responses on the socket and put them in a static hashtable that the senders will be waiting on. The senders will pull the value from the hash if it is the response associated with their request.

Is there a better design for this? Is it possible to use a callback method in Java to read the responses from the socket?

My concern is maintaining this separate thread for reading the responses and being able to identify if the thread dies or is not working properly.

Any ideas?
 
Rob Spoor
Sheriff
Posts: 20903
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use a BlockingQueue for the messaging. Each thread get its own BlockingQueue to read from. The client reads something from the socket, finds the matching thread's BlockingQueue and writes something to it. This does mean that these threads will block until there is data for them.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!