Some general Java NIO questions

Hello,
today I have started with Java NIO, but it seems to be quite complex, hence I have some questions to which I couldn’t find any answer in those NIO tutorials I have read.

For learning purposes I want to implement some very common use cases:

  1. Sending serialized objects to a server, deserializing and storing them in a collection.
  2. Requesting data from a server. The data could be anything, maybe some objects in an array.

I don’t understand how ObjectInputStream/ObjectOutputStream and ByteBuffer work together and I’m not sure how many channels I need on the client and on the server. Do I need one socket channel on each side for each use case (4 socket channels altogether) or would one read-write-socket channel on each side be sufficient?

Thanks for all answers.

Why did you decide to use NIO? It’s not a natural progression from old IO. You’re better off without it, even if you merely want to learn it for the sake of it - just don’t. At least, not until you have a solid understanding of old IO, and a specific need for new IO.

Normal sockets need multiple threads to handle multiple clients concurrently, which would result in a cumbersome and resource-hungry multithreading implementation.

Unless you actually have thousands of concurrent connections, it’s premature optimization.

My goal is to get just a basic practical understanding of how this works, because it doesn’t have a lot in common with standard Java sockets. It just aroused my interest, the practical usage is another question.

Given the questions in your first post (how to connect Streams to Channels, and whether to use 1 or 2 sockets per client), I’m fairly sure you simply need to study old IO and get real world experience with it (not just a simple request/reply server), before even considering NIO. Once you have experience with old IO, you’ll see that NIO is not that different and all NIO tutorials will make sense.

That was a typo and I already changed that. I did not mean sockets, but socket channels.

Same thing really. A NIO channel is an InputStream and OutputStream wrapped into one.

With the new concurrent libraries and executor services threading is a piece of cake. You can now write a standard IO socket based server with threading that is dead simple compared to the old thread way or even with NIO.