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 Computing
Conference & Expo
November 2-4, 2009 NYC
Register Today and SAVE !..

2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
In many cases, the end of the year gives you time to step back and take stock of the last 12 months. This is when many of us take a hard look at what worked and what did not, complete performance reviews, and formulate plans for the coming year. For me, it is all of those things plus a time when I u...
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()); ?


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);
SOA World Latest Stories
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used t...
Containers and Kubernetes allow for code portability across on-premise VMs, bare metal, or multiple cloud provider environments. Yet, despite this portability promise, developers may include configuration and application definitions that constrain or even eliminate application portabil...
Most DevOps journeys involve several phases of maturity. Research shows that the inflection point where organizations begin to see maximum value is when they implement tight integration deploying their code to their infrastructure. Success at this level is the last barrier to at-will d...
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus ...
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one l...
In his session at 20th Cloud Expo, Scott Davis, CTO of Embotics, discussed how automation can provide the dynamic management required to cost-effectively deliver microservices and container solutions at scale. He also discussed how flexible automation is the key to effectively bridging...
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