Java Industry News
Frank's Java Code Stack #5
Creating Non-Blocking Sockets
Frank's Java Code Stack #5
Creating Non-Blocking Sockets
Jan. 1, 2000 12:00 AM
(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.
#10 |
Mike Roper commented on 18 Mar 2003
Frank, don't apoloize, just keep writing cool articles like this one and the more recent MBean article. :)
|
#9 |
LK commented on 22 Nov 2002
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.
|
#8 |
Kenneth commented on 22 Nov 2002
What's wrong with :
e.printStackTrace(System.out);
|
#7 |
Frank Jennings commented on 22 Nov 2002
Exception object can never be null, as it is inside the catch block. e.getMessage() is a neat way to do.
|
#6 |
mthreat commented on 21 Nov 2002
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..
|
#5 |
Frank Jennings commented on 21 Nov 2002
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.
|
#4 |
Frank Jennings commented on 20 Nov 2002
Hey guys! chill out. If I had hurt any of u...I apologize. I wont use such derogatory statement in future. Java Rules!
|
#3 |
Jonathan Stokes commented on 20 Nov 2002
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.
|
#2 |
rob commented on 20 Nov 2002
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!
|
#1 |
Tor I. Wilhelmsen commented on 20 Nov 2002
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()); ?
|