non-blocking read in java

Started by
1 comment, last by cignox1 19 years, 8 months ago
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!
Advertisement
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.
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!

This topic is closed to new replies.

Advertisement