I am implementing a simple file server using Java NIO with one selecting thread and multiple worker threads(for performing real read/write).
The main part of the cod
Why? The read won't block. Do it in the current thread. You are just in for endless problems this way. You will have to deregister OP_READ before you hand over to the read thread, which is easy enough, but the hard part is that when the read thread completes the read it will have to re-register OP_READ, which requires either (i) a selector wakeup(), which causes the select thread to run when there is possibly nothing to do, which is wasteful, or else (ii) use a queue of pending reregistrations, which delays the next read on that channel until after the next time the selector wakes up, which is also wasteful, or else you have to wakeup the selector immediately on adding to the queue, which is also wasteful if nothing is ready. I've never seen a convincing NIO architecture that used different select and read threads.
Don't do this. If you must have multithreading, organize your channels into groups, each with its own selector and its own thread, and have all those threads do their own reading.
Similarly there is no need to write in a separate thread. Just write when you have something to write.
For NIO, just keep one principle in mind: Do read/write in the main select thread. This principle is the reflection of the hardware nature. Don't worry that read in main select thread is not swift. In modern server, CPU is always faster than network card. So no-blocking read in one thread is also faster than network card operations. One thread is already enough to read packet. We needn't any more threads.