Digital Edition

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.


1. import java.nio.*;
2. import java.nio.channels.*;
3. import*;
4. import*;
6. public class nbsock{
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 =;
15. ssc.configureBlocking(false);
17. /* Binding Address and port */
18. ssc.socket().bind
(new InetSocketAddress(port));
19. } catch (IOException e) {
20. System.out.println(""+e);
21. }
22. }
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 =;
32. sc.configureBlocking(false);
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. }
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);
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()) {}
61. /* Socket channel is ready */
62. System.out.println("Channel Ready!");
63. } catch (IOException e) {
64. System.out.println(""+e);
65. }
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.

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 :


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()); ?

Subscribe to the World's Most Powerful Newsletters


"We started a Master of Science in business analytics - that's the hot topic. We serve the business ...
The standardization of container runtimes and images has sparked the creation of an almost overwhelm...
As DevOps methodologies expand their reach across the enterprise, organizations face the daunting ch...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As au...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news an...
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held Novemb...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO an...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, ...
As you move to the cloud, your network should be efficient, secure, and easy to manage. An enterpris...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing w...
@DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held Novem...
DXWorldEXPO LLC announced today that Dez Blanchfield joined the faculty of CloudEXPO's "10-Year Anni...
There is a huge demand for responsive, real-time mobile and web experiences, but current architectur...
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its ...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will ...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to ...
"NetApp is known as a data management leader but we do a lot more than just data management on-prem ...
We call it DevOps but much of the time there’s a lot more discussion about the needs and concerns of...
The dynamic nature of the cloud means that change is a constant when it comes to modern cloud-based ...
"Since we launched LinuxONE we learned a lot from our customers. More than anything what they respon...