Using Serialization with non-blocking sockets

Posted by Strainu on November 11, 2007

The most common way to make a server in Java is to create a thread pool and associate each request with a thread. Java5 offers a special class called Executor that can help you with the task. However, if you ever needed to make a server which can handle thousands of connections, you know this solution doesn’t scale very well. Most processors can’t handle more than a few hundreds of threads.
The solution is to use non-blocking sockets, a feature introduced in java 1.4 (the java.nio package). However, this has an important drawback: you can’t use the getInputStream(), getOutputStream() functions from the Socket class to serialize objects. The reason is simple: with non-blocking sockets, there is no way the system can guarantee that the whole object has been sent/received.
You can however “trick” the virtual machine by using explicit Streams. You have a simple example below. We try to send an object with the Message type.

The code works if you receive the whole object or more than one object (the readObject() function reads exactly one object). However, I had some issues with reconstructing the object if it arrived in multiple pieces. Any suggestions on that part would be useful.
Here are some resources that I found useful: a discussion at and another discution about the subject.

Share and Enjoy:
  • Facebook
  • Twitter
  • LinkedIn
  • Reddit
  • Add to favorites

2 Comments to Using Serialization with non-blocking sockets

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.