Sign in to follow this  

non-blocking read in java

This topic is 4868 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, It is my second java application using Socket, and only now I discovered that Java doesn't support non-blocking socket I/O (I wonder how my first program worked correctly, since I used available()). I know that starting from version 1.4 there is NIO, but for many reasons I cannot use it. So the question is: how to get a non-blocking behaviour? I think that the only working solution is using threads, but should I really manage 4 threads for just 2 connections (2 for input, 2 for output)? And what is the better (thus simple: I don't need very high quality architectures...) design? Is there some tutorial or resources? Thank you!

Share this post


Link to post
Share on other sites
You pretty much have to use either NIO or threads. Why can't you use Java 1.4? Even if you're distributing the application to people who might not have 1.4, you can give them a client program that uses threads, but use NIO on your server (where it really counts).

If you do use threads, I'd suggest having each read thread put messages into a global queue as it reads them, and each send thread read messages to send from another queue. Then your server or logic code can run in a single thread, and you only need synchronized blocks when accessing these queue objects.

Share this post


Link to post
Share on other sites
I cannot use NIO because server and clients will run on a local network (don't know if it runs the 1.4). Since client and server are the same program (just running in different modes) I think it would be better not to specialize the code, mantaining it simpler. I will go with threads, even if I still think that if the available() method worked, simple program as mine one would be easier to make...sigh!
Thank you for the help!

Share this post


Link to post
Share on other sites

This topic is 4868 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this