• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Asynchronous socket programming in Java

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Sheriff
Posts: 22791
131
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic