Java poll on network connections
Asked Answered
C

2

4

I am writing a program in Java where I have opened 256 network connections on one thread. Whenever there is any data on a socket, I should read it and process the same. Currently, I am using the following approach :

while true
do
   iterate over all network connections
   do
         if non-blocking read on socket says there is data
         then
               read data
               process it
         endif
   done
   sleep for 10 milli-seconds
done

Is there a better way to do the same on Java ?? I know there is a poll method in C/C++. But after googling for it, I did not get concrete idea about Java's polling. Can somebody explain this ??

Calumniation answered 19/3, 2013 at 6:54 Comment(6)
Just a thought...Is 256 network connections for one process not a bit excessive?Mcrae
You could create one blocking read thread for each network connection. This way you won't iterate over the connections (it is done by the OS I think) and the thread will wake up when data arrives (no more need for sleep).Trawler
@Quirliom It is needed by the program. I cannot reduce the number of connections.Calumniation
@Trawler This will complicate the programming model. I do not want to invest so much time on this thing when blocking + polling primitives are already provided by the Linux kernel.Calumniation
How does a thread wake up? Does connection automatically wake it? Or do we need something else?Bonniebonns
256 network connections a bit excesive? There are examples of servers that handle x100 x10000 that ammounts.Links
M
1

The java.nio package sounds right for what you want to do. It provides ways to perform asynchronous IO.

Moores answered 19/3, 2013 at 7:22 Comment(1)
It also provides ways to perform non-blocking and multiplexed I/O, which sound more like what he wants to do.Snotty
H
2

Take a look to http://netty.io/ (this is a non-blocking framework to build network application on java). https://community.jboss.org/wiki/NettyExampleOfPingPongUsingObject - 'hello world' on netty.

Hamburger answered 19/3, 2013 at 7:30 Comment(0)
M
1

The java.nio package sounds right for what you want to do. It provides ways to perform asynchronous IO.

Moores answered 19/3, 2013 at 7:22 Comment(1)
It also provides ways to perform non-blocking and multiplexed I/O, which sound more like what he wants to do.Snotty

© 2022 - 2024 — McMap. All rights reserved.