Comments
yourfanat wrote: I am using another tool for Oracle developers - dbForge Studio for Oracle. This IDE has lots of usefull features, among them: oracle designer, code competion and formatter, query builder, debugger, profiler, erxport/import, reports and many others. The latest version supports Oracle 12C. More information here.
Cloud Expo on Google News
SYS-CON.TV
Cloud Expo & Virtualization 2009 East
PLATINUM SPONSORS:
IBM
Smarter Business Solutions Through Dynamic Infrastructure
IBM
Smarter Insights: How the CIO Becomes a Hero Again
Microsoft
Windows Azure
GOLD SPONSORS:
Appsense
Why VDI?
CA
Maximizing the Business Value of Virtualization in Enterprise and Cloud Computing Environments
ExactTarget
Messaging in the Cloud - Email, SMS and Voice
Freedom OSS
Stairway to the Cloud
Sun
Sun's Incubation Platform: Helping Startups Serve the Enterprise
POWER PANELS:
Cloud Computing & Enterprise IT: Cost & Operational Benefits
How and Why is a Flexible IT Infrastructure the Key To the Future?
Click For 2008 West
Event Webcasts
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()); ?


Your Feedback
Mike Roper wrote: Frank, don't apoloize, just keep writing cool articles like this one and the more recent MBean article. :)
Frank Jennings wrote: Exception object can never be null, as it is inside the catch block. e.getMessage() is a neat way to do.
mthreat wrote: 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..
Frank Jennings wrote: 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.
Frank Jennings wrote: Hey guys! chill out. If I had hurt any of u...I apologize. I wont use such derogatory statement in future. Java Rules!
Jonathan Stokes wrote: 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.
rob wrote: 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!
Tor I. Wilhelmsen wrote: 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()); ?
LK wrote: 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.
Kenneth wrote: What's wrong with : e.printStackTrace(System.out);
Latest Cloud Developer Stories
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Deve...
As Cybric's Chief Technology Officer, Mike D. Kail is responsible for the strategic vision and technical direction of the platform. Prior to founding Cybric, Mike was Yahoo's CIO and SVP of Infrastructure, where he led the IT and Data Center functions for the company. He has more...
Cloud computing delivers on-demand resources that provide businesses with flexibility and cost-savings. The challenge in moving workloads to the cloud has been the cost and complexity of ensuring the initial and ongoing security and regulatory (PCI, HIPAA, FFIEC) compliance acros...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging ...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 ...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021



SYS-CON Featured Whitepapers
ADS BY GOOGLE