Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

what to use Ordinary threads or java.nio ?  RSS feed

 
Meir Yan
Ranch Hand
Posts: 599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all
im trying to decide if to use the java.nio threads for non blocking mechanism
or to stick to the standard java threads
i need it to be able to serve lots of tcp requests / response
and to be multi platform what is the pros and cons of java.nio .
Thanks
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, there's no such thing as nio threads. Threads are threads, whatever you use them for. If you're using JDK 5 or later, you'd probably be better off using the more general concept of an Executor rather than a Thread, but that's a separate issue.

If you use traditional IO, you will probably need one thread on the server for every connected client. If you have a lot of clients, that could be a lot of resources - even if, at any instant, most of the clients aren't doing anything. But if you use NIO's nonblocking classes for IO, you don't need as many threads. You probably still need multiple threads, but probably not nearly as many. Typically you can use a thread pool which is approximately as big as the number of clients who are likely to be active at the same time. Most humans have seconds or even minutes between actions online, and so at the millisecond level, there's a lot of dead time where individual clients aren't doing anything. No need to waste threads on them in this case.

The main downside of NIO classes is that they're generally harder to use than traditional IO. They were designed for high performance in certain situations... not simplicity. As a result, I wouldn't recommend using NIO directly unless you're already confident you know how to implement a traditional IO solution, and know why that's undesirable in this case. (Assuming your load and performance requirements are such that it is undesirable.)

However, a good alternative is to use another library which encapsulates the NIO classes and hides much of their complexity from you, while putting the pieces together to provide a solid framework for serving a large number of concurrent users. Two possibilities for this are Apache MINA or Grizzly. I don't know which of these would be better for you, but I would recommend looking into them.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!