Digital Edition

SYS-CON.TV
Frank's Java Code Stack #5 Creating Non-Blocking Sockets
Frank's Java Code Stack #5 Creating Non-Blocking Sockets

(November 18, 2002) - Most of the Java developers I have come across create multi-threaded servers without knowing a jack about deadlocks, I/O Performance, Thread starvation, scalability and other OS dependent issues. While forking new thread for every socket connection and managing predefined thread pools are the most-taught techniques, robust servers can be written for enabling multiple simultaneous connections with a single thread configured with Non-blocking sockets using Java's NIO socket channels. Coding Non-blocking I/O for sockets and files was introduced with JDK1.4 NIO APIs. Let's create a simple Non-blocking server socket and a client socket.

Code:

1. import java.nio.*;
2. import java.nio.channels.*;
3. import java.io.*;
4. import java.net.*;
5.
6. public class nbsock{
7.
8. /* Creating a Non-blocking Server
9. socket */
10. public static void mySsc(int port){
11. try{
12. /* Create a non-blocking server
13. socket channel on port 8678 */
14. ServerSocketChannel ssc =
ServerSocketChannel.open();
15. ssc.configureBlocking(false);
16.
17. /* Binding Address and port */
18. ssc.socket().bind
(new InetSocketAddress(port));
19. } catch (IOException e) {
20. System.out.println(""+e);
21. }
22. }
23.
24. /* Creating a Non-blocking
25. Client Socket */
26. public static SocketChannel mysc
(String host, int port){
27. SocketChannel sc=null;
28. try{
29. /* Create a non-blocking
30. socket channel */
31. sc = SocketChannel.open();
32. sc.configureBlocking(false);
33.
34. /* A Non-blocking connection
35. request to the server */
36. sc.connect(new InetSocketAddress
(host, port));
37. }catch (IOException e) {
38. System.out.println(""+e);
39. }
40. return sc;
41. }
42.
43. public static void main(String ar[]){
44. try {
45. /* Create a non-blocking
46. socket channel */
47. mySsc(8678);
48. SocketChannel sc = mysc("afj", 8678);
49.
50. /* Completing the connection by
51. calling finishConnect().
52. If this channel is in non-blocking
53. mode then this method will return
54. false if the connection process
55. is not yet complete. If this channel
56. is in blocking mode then this
57. method will block until the
58. connection either completes or fails. */
59. while (!sc.finishConnect()) {}
60.
61. /* Socket channel is ready */
62. System.out.println("Channel Ready!");
63. } catch (IOException e) {
64. System.out.println(""+e);
65. }
66.
67. }
68. }

Socket channels are not an absolute abstraction of connecting network sockets. Binding, shutdown, and the manipulation of socket options must be done through an associated socket object which can obtained by invoking the socket() method. Socket channels are safer for use by multiple concurrent threads. The connect() and finishConnect() methods are mutually synchronized , and an attempt to initiate a read or write operation while an invocation of one of these methods is in progress will block until that invocation is complete.

Assignment
Try using a selector to manage Non-blocking sockets and accept connection requests. Hint: Use the java.nio.channels.Selector class.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Frank, don't apoloize, just keep writing cool articles like this one and the more recent MBean article. :)

Being able to service multiple sockets with a single thread rocks. But to fully appreciate it you need to code a simple server and then scale it. Then the method used to log errors will seem properly trivial (although there have been recent advances in logging as well). But really you have to catch on fire once to fully appreciate this fire hose.

What's wrong with :

e.printStackTrace(System.out);

Exception object can never be null, as it is inside the catch block. e.getMessage() is a neat way to do.

e.toString() risks a NullPointerException if e is null, while "" + e will just print out "null" if e is null. Which one is better? That's a matter of opinion..

Thanks Jon!.
System.out.println(""+e) sure is ugly. I prefer logging error messages than doing a console out, but the code provided in this column is just a snippet for introducing a lesser known technique. And it is no way complete or robust. It is upto you to extend these code capabilities.
Creating Non-blocking sockets were always there in other langauges like fcntl() in C.

Hey guys! chill out. If I had hurt any of u...I apologize. I wont use such derogatory statement in future. Java Rules!

This is frivolous, but I can't let the only replies be trivially negative.
(1) Who uses System.out.println() in production code anyway? It's just an example.
(2) Non-blocking I/O is new TO JAVA, it's not new, but rather 'old.'

I'd frankly rather *not* worry about deadlocks, I/O Performance, Thread starvation, etc., but it is often necessary to code using lower levels of abstraction for the sake of scalability.

Thanks for the nice example, Mr. Jennings. I especially appreciate your article's brevity.

Yeah your right most developers don't know jack about NIO, that's because IT IS NEW!!!! They can't spend all their time reading APIs and reworking code that already works just because a new method has been introduced.

If you want people to look at your suggestions, I would suggest that phrases like "without knowing a jack" be ommited. Most developers are hardworking and have lives outside of Java Programming!

In this day and age I had hoped to avoid ever seeing an abomination like System.out.println(""+e); What is wrong with the far more efficient System.out.println(e.toString()); ?




ADS BY GOOGLE
Subscribe to the World's Most Powerful Newsletters

ADS BY GOOGLE

The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news an...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing w...
Disruption, Innovation, Artificial Intelligence and Machine Learning, Leadership and Management hear...
Enterprises are striving to become digital businesses for differentiated innovation and customer-cen...
DXWorldEXPO LLC announced today that Telecom Reseller has been named "Media Sponsor" of CloudEXPO | ...
"Calligo is a cloud service provider with data privacy at the heart of what we do. We are a typical ...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As au...
"We host and fully manage cloud data services, whether we store, the data, move the data, or run ana...
Enterprise architects are increasingly adopting multi-cloud strategies as they seek to utilize exist...
In this Women in Technology Power Panel at 15th Cloud Expo, moderated by Anne Plese, Senior Consulta...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitori...
Adding public cloud resources to an existing application can be a daunting process. The tools that y...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, ...
Discussions of cloud computing have evolved in recent years from a focus on specific types of cloud,...
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use ...
In an era of historic innovation fueled by unprecedented access to data and technology, the low cost...
DXWorldEXPO LLC announced today that "IoT Now" was named media sponsor of CloudEXPO | DXWorldEXPO 20...
In this presentation, you will learn first hand what works and what doesn't while architecting and d...
Everyone wants the rainbow - reduced IT costs, scalability, continuity, flexibility, manageability, ...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT...